Posts about Angular

Codespaces config for .NET Angular project

After creating a working dev container configuration for an ASP.NET Core with Angular project, I wanted to also try it out with GitHub Codespaces. I had to do additional changes to the configuration to get it working.

Dev container config for .NET Angular project

For simple projects with a single technology stack, you're likely to find a dev container template preconfigured with everything you need. That's what happened to me when I created my first dev container. For larger projects with more than one technology stack, more configuration will be needed.

Scroll to top on navigation in Angular

November 4th 2022 Angular

When we navigate between static web pages, we are used to the target page scrolling up. In Angular applications with routing, this is not the case by default. However, there is a built-in option to enable this behavior.

Multiple service instances in Angular

October 28th 2022 Angular Dependency Injection

By default, services in Angular are treated as singletons – the same instance is used throughout the application. If this is not the desired behavior, you can change it by removing the providedIn property from the Injectable decorator for the service and then add the service as a provider to each component.

Cross-component Angular Forms

July 29th 2022 Angular

Most examples of Angular Reactive Forms are implemented as single components. But it does not have to be that way. Parts of a form can be implemented as a separate component, although there are some limitations to this. This makes it much easier to manage large, hierarchically structured forms.

Inspecting previous page in Angular

June 10th 2022 Angular

You can use Angular Location service to implement programmatic backward navigation from non-root pages. However, if the user has used a non-root URL to navigate to your application, they will navigate out of the application in this way. You may want to detect this and navigate them back to the root page instead when this happens.

Debounce search calls in Angular

April 8th 2022 Angular ReactiveX

In a recent blog post, I addressed the issue of debouncing user input in Blazor applications. In Angular, we could use a debounce helper function like _.debounce from Underscore.js to achieve this. But to have more control over it, we can use RxJS just like in Blazor. This makes even more sense because Angular also uses RxJs a lot internally, for example in its HTTP client API.

Shared Angular library without NPM

February 18th 2022 Angular

Angular CLI includes all the tools you need to develop shared libraries that can be used in multiple applications, as long as they are all in the same workspace. However, it does not work without modifications if the library is in a separate workspace. Fortunately, this is still possible, although the process does not seem to be well documented.

Custom event types in Ionic

February 11th 2022 Ionic 4+ Angular TypeScript

In Ionic 6, component events have well-documented, strongly typed arguments. Unfortunately, the outputs in Angular are still typed as Event. The issue has already been reported and there is even a fix for it, but it did not make it into Ionic 6 as it would involve a breaking change. So until the fix is released, you'll have to settle for one of the workarounds.

Generic base components in Angular

December 10th 2021 Angular TypeScript

Type checking in Angular is constantly improving. In newer versions, it even does a good job in templates. This can help us detect errors in our code earlier. However, sometimes extra work is needed to take full advantage of this feature.

Strongly typed ng-template in Angular

December 3rd 2021 Angular TypeScript

The ng-template element in Angular allows you to reuse parts of a component template, which in a sense makes it a lightweight subcomponent. By default, its context is not typed, but it can be made strongly typed with a little trick.

Mouse wheel scrolling in Angular

October 22nd 2021 Angular

When you enable scrolling for an HTML element with content that overflows vertically, browsers automatically support scrolling with the mouse wheel when you hover over that element. This is not the case when the content overflows horizontally. To support this, some JavaScript code is required.

Interfaces in Angular dependency injection

October 15th 2021 Angular Dependency Injection

Angular's dependency injection makes it really easy to inject services into components and other services. In most cases, that's all we need. But what if we need more than one implementation of the same service contract? To accomplish this in strongly typed languages, we typically create interfaces as contracts that can be implemented by multiple services. When an instance of the interface is requested, the correct implementation is injected based on the dependency injection configuration. In Angular, this does not work.

Mocking current time with Jasmine

October 1st 2021 Angular Unit Testing

In an Angular application, I wanted to test a functionality that depends on the current time (by calling Jasmine has great built-in support for spying on methods, so my first approach was to create a spy for that would return different values during testing. And it worked. It was not until later that I realized there was an even more elegant way to do this.

Handle missing images in Angular

September 24th 2021 Angular

When displaying images in an Angular application (or any other web application), you need to ensure that the images exist so that the placeholder for the broken image is not rendered by the browser.

Testing timers with fakeAsync

September 17th 2021 Angular Unit Testing

Angular's fakeAsync zone is a great tool for unit testing asynchronous code. Not only does it make it easy to wait for promises and observables to resolve, but it also gives you control over the passage of time. This makes it a nice alternative to Jasmine's Clock when working with Angular.

Asynchronous pipes in Angular

September 10th 2021 Angular

Angular expects pipes to be synchronous. They should return a resolved value, not a Promise or an Observable. To use a pipe that returns an unresolved value, you can use Angular's async pipe. If that's not an option, you can resolve the asynchronous value inside the pipe if you make it impure, as I describe below.

Efficient impure pipes in Angular

September 3rd 2021 Angular

Angular pipes are a useful tool for formatting values for display. However, they may not work as expected for composite objects.

Testing failing HTTP requests in Angular

August 27th 2021 Angular Unit Testing

I really like Angular's support for unit testing HTTP requests, even if I find the documentation a bit spotty. I struggled a bit when I first tried to test error handling.

Testing HttpClient GET requests in Angular

August 20th 2021 Angular Unit Testing

Angular does a lot to make testing your code easier. This includes a dedicated module for testing HttpClient code. However, the way HttpTestingController matches requests makes it unnecessarily difficult to test GET requests with query parameters.

Angular testing: flush vs. flushMicrotasks

July 2nd 2021 Angular Unit Testing Async

Much of the Angular code is asynchronous. The fakeAsync function is very useful when testing such code, especially when not all promises and observables are publicly accessible. You can use the flush function instead of awaiting them individually. I recently learned that this does not work in all cases.

Using SCSS variables in Angular

February 12th 2021 Angular Visual Studio Code

When creating a new project using Angular CLI you can choose to have SCSS support in the project preconfigured. But even if you do, it doesn't set up any file for the rules that will be reused across components (such as variables, functions, and mixins).

Configuring Angular for older browsers

February 5th 2021 Angular

In recent versions, Angular is preconfigured for an ES2015 build which only works in modern browsers. Often, that's not an issue. Fortunately, it's still possible to make it compatible with older browsers (e.g. Internet Explorer or old Chromium versions in embedded devices) when that's a requirement.

Component-level services in Angular and testing

By default, services in Angular are provided at the root module level. This way, the same instance of the service will be injected into any component depending on it. If a component needs a separate instance of the service for itself and its children, it can change the scope by declaring a service provider itself. However, this change also affects dependency injection in tests.

Testing Angular lifecycle hooks

January 1st 2021 Angular Unit Testing

There's no specific guidance for testing Angular lifecycle hooks in the component testing scenarios covered by the Angular documentation. Maybe because they can be tested like any other method: a test can set up the component state and then manually invoke the hook. However, some caution is needed since hooks can also be called implicitly by Angular.

No Value Accessor Error in Angular Tests

October 2nd 2020 Angular Unit Testing

I was recently tasked with troubleshooting failing Angular unit tests for a component in a large codebase I was completely unfamiliar with. The tests were failing with: "Error: No value accessor for form control with unspecified name attribute".

Scroll-dependent Animation in Ionic

April 24th 2020 Ionic 4+ Angular

In my previous blogpost, I implemented a staggered animation in Ionic Angular where the animation-delay depended only on the position of the item in the list. This time, the delay will depend on the current scroll position of the list. The animation will start in the middle of the screen and move towards the top and bottom edges.

Staggered Animation in Ionic Angular

April 17th 2020 Ionic 4+ Angular

Recently, Josh Morony published an interesting tutorial about staggered animations in Ionic. Since he's using StencilJS, there are some syntax changes required to make his sample code work with Angular. It wasn't as trivial as I expected.

Forcing Reload of Root Page in Ionic 4

February 14th 2020 Ionic 4+ Angular

Angular based routing in Ionic 4 introduces some gotchas if you're used to navigation in Ionic 3. Reinitializing the navigation stack by setting the root to the same page as it was before is one of those gotchas.

Mocking Fetch Calls with Jasmine

January 10th 2020 Unit Testing Ionic 4+ Angular

After getting asset loading working in Ionic unit tests, I wanted to also test the error handling in case an asset fails to load. Mocking the fetch call would be the easiest way to do that.

Assets Not Loading in Ionic Unit Tests

December 27th 2019 Ionic 4+ Unit Testing Angular

Recently I had to embed a JSON file as an asset in my Ionic 4 project. When I tried to test the code accessing the asset, I was unpleasantly surprised. The asset failed to load with a 404 error. The body of the response was "NOT FOUND".

Ionic 4: Pinned Certificates in Output Folder

November 15th 2019 Ionic 4+ Angular

If you want to use certificate pinning in Ionic 4 applications, the Cordova Advanced HTTP plugin is your best option. There's even an Ionic Native wrapper available for it to make it easier to use. In this post I'm focusing on how to put the certificates into the output folder as required by the certificate pinning functionality despite that folder being deleted at the beginning of every build.

Repeating Same Ionic 4 Page in History

November 8th 2019 Ionic 4+ Angular

In Ionic 3, there was no need to pay any attention which pages you navigate to and how. This made it easy to create pages for navigating hierarchical structure, e.g. a catalog. In Ionic 4, the same route can't repeat in the history stack.

View Encapsulation After the Ionic 4 Upgrade

August 30th 2019 Ionic 4+ Angular

Angular supports several different modes of encapsulating styles in components so that styles from one component don't affect elements in other components. By default, Angular uses ViewEncapsulation.Emulated to emulate native Shadow DOM behavior without actually using Shadow DOM. Ionic 4 uses the same default which can cause problems when upgrading applications from Ionic 3 where ViewEncapsulation.None was used.

Inspecting Angular Apps from Browser Console

July 19th 2019 Angular Ionic 2/3 Ionic 4+

Many JavaScript developers are used to inspecting the web page and the state of JavaScript variables using the browser developer tools. The browser console window can even be used for executing arbitrary JavaScript code to affect the web page/application at runtime. However, when using a SPA framework like Angular instead of vanilla JavaScript it's not as easy anymore to access the JavaScript objects of interest such as components and services. Fortunately, Angular provides means to access them, although they aren't documented well.

Angular Directive for a Specific Component

July 5th 2019 Angular

Some Angular directives only make sense when they are applied to a specific Angular component. For example, the host component might be injected in the directive constructor so that directive code can manipulate it.

Switching Angular Services at Runtime

A while ago I've already written a blogpost on how to inject a different Angular service implementation based on a runtime value. With that approach, the selected service was initialized at startup and remained the same for the entire application lifetime. In response to that blogpost, I received a question how one could switch between the implementations while the application is running. This blogpost is my detailed answer to that question.

Programmatic Submit for Angular HostListener

February 15th 2019 Angular

The HostListener decorator can be used in Angular directives to listen to events triggered by the host element to which the directive is attached. For example, one could listen to the submit event of a form. However, this will not work for any programmatic attempts to submit a form.

Handling the Paste Event in Angular

February 8th 2019 Angular

After using a framework for a significant amount of time, you gain confidence that you understand it well. But you might still have incorrect assumptions which don't affect your work most of the time. I learned that about Angular recently when I wanted to handle the paste event for an input element.

Beware of Optimized Angular Change Detection

August 3rd 2018 Angular

Updating of views in Angular is fully dependent on its change detection. I've already written a post on how code executed outside NgZone can be missed by change detection. But Angular's highly optimized change detection code can bite you in other scenarios as well. If it determines that the same value has been assigned, it doesn't propagate the change which can break intended functionality.

Using Embedded Angular Templates

July 27th 2018 Angular

When you want to reuse a part of markup in Angular, you usually wrap it into a separate component. However, sometimes a component can be an overkill. You might have only a couple of lines of markup which you need to repeat in multiple places inside a single component but nowhere else. In that case, embedded templates could be just the right tool for the job.

Provider Instances in Lazy Loaded Modules

July 20th 2018 Angular Ionic 2/3

If you're developing applications for Ionic or Angular, you have probably already encountered static forRoot() and forChild() methods which you need to call when importing other modules, such as ngx-translate. You might not be fully aware of their significance, but when developing your own shared modules, you'll likely need to learn more about them.

Ionic Global Error Handler

March 30th 2018 Ionic 2/3 Angular

During development, Ionic replaces the default Angular error handler with its own implementation which displays the error details in a page overlay instead of just printing them out to console. If you want to automatically report these unhandled errors to your analytics service, you can replace that error handler with your own custom one.

Angular DOM Sanitization in Ionic

March 23rd 2018 Ionic 2/3 Angular

Angular comes with built-in Cross Site Scripting (XSS) protection, which prevents you from using unverified dynamic values in certain contexts inside your generated page. Most of the time you shouldn't even notice this. But when you do, it's good to know how you can work around the restrictions set by this protection.

Creating HTML Comments in Angular

March 16th 2018 Angular

Although comments in HTML markup usually don't play an important role (they are comments after all), they could have a meaning for parsers which post-process the HTML document. When I recently encountered such a requirement, it turned out that generating custom HTML comments with an Angular application is not as easy as one might expect.

Querying ContentChildren of Unknown Type

October 20th 2017 Angular Ionic 2/3

To reference DOM elements in the component template from the component code, ViewChild and ViewChildren decorators can be used. Similarly, ContentChild and ContentChildren decorators will provide access to DOM elements in the component content. Still, I had a hard time coming up with a way to support a scenario where the component consumer should be able to tag some of the DOM elements that need to be processed by the component.

Access Parent Component from Angular Directive

October 13th 2017 Angular Ionic 2/3

Angular directives are a great way to extend behavior of Angular components and HTML elements. As long as you only need a reference to the host HTML element to implement your functionality, Angular dependency injection will easily inject it as an ElementRef, along with a Renderer to modify it. If you also require a reference to the host component, it gets a little more complicated.

Hidden Advanced Features of Ionic's Slides

October 6th 2017 Ionic 2/3 Angular

Slides is a very flexible Ionic component for presenting multiple slides to the user who can swipe between them. However, not all its customization options are exposed as Angular Inputs and Outputs or even fully documented. To see all supported options, one can peek into the source code. The only way to learn more about them is to check the Swiper API reference, which the Slides component is based on.

Faster Ionic Tests Without TestBed

September 15th 2017 Ionic 2/3 Unit Testing Angular

Although the official Ionic templates aren't preconfigured for unit testing, there is no lack of guidance in this field. It's not all that difficult to get started with unit testing any more. However, as the number of tests in the project will start to increase, it will soon become obvious that the test are quite slow.

Configuring VS Code for Ionic Development

I've been doing a lot of Ionic 2 development lately in Visual Studio Code lately. The editor has great out-of-the-box support for TypeScript, HTML and CSS editing. There's also a lively ecosystem for extensions, which can improve the development experience even further. I'm going to describe my current configuration and the selection of extensions that I'm using.

Generating Swagger Client-side Code

The biggest advantage of having a formal description for a RESTful API is the ability to programmatically generate client-side code for calling the service. Unfortunately, it turned out that Swagger tooling still leaves much to be desired, at least for generating TypeScript Angular code.

Change Detection in Non-Angular Callbacks

June 9th 2017 Angular Ionic 2/3

Recently, I was troubleshooting a curious bug that only happened on one page in my Ionic 2 application: new values from an HTTP request only showed on the page after a click instead of immediately. Wrapping the update code in helped. However, it bothered me why this was only necessary in this single instance.

Dynamic Dependency Injection in Angular

I keep getting impressed by how feature-rich dependency injection in Angular is. This time I needed it to inject the appropriate implementation of a dependency based on runtime information. Of course, the scenario is well supported.

Intercept HTTP Requests in Angular and Ionic 2

Angular has an impressive dependency injection system, however some aspects could be documented better. Old blog posts explaining how things worked before the final release don't help either. Hence, it took me a while to successfully intercept HTTP requests and inject a common parameter.

Custom Angular Validators with Dependencies

April 21st 2017 Angular Ionic 2/3 TypeScript

Angular has great support for validating data in forms, both template-driven and and reactive ones, built imperatively with FormGroup. It is also easy to create own custom validators. However, I did not find it obvious, how to use injected dependencies in non-directive validators for reactive forms.

Sharing Ionic 2 Code Between Projects

April 7th 2017 Ionic 2/3 Angular Git

Ionic 2 includes many components and native wrappers out of the box. However, you will probably want to share some of your own code between projects if you are working on more than one of them and they are at least remotely similar. Since Ionic 2 builds on top of Angular, shared modules are the right tool for the job.

Importing JavaScript Libraries in Angular

February 24th 2017 TypeScript Angular

Angular makes heavy use of ECMAScript 2015 modules. All components and other Angular objects are modules themselves, therefore the tutorials explain early on, how to import and use them. However, how does one import a third party library which still exports legacy CommonJS or AMD modules?

Challenges of Ionic 2 Production Builds

February 17th 2017 Ionic 2/3 Angular TypeScript

By default, Ionic 2 produces unminified development builds. To force an optimized production build, you need to add --prod switch to ionic build or ionic run command. Since development build doesn't include Angular AoT (Ahead of Time) compilation, your production build might turn out broken even if development build of the application worked just fine.

Angular Tutorial with Async and Await

January 27th 2017 Async TypeScript Angular

In version 2.1 that was released in December 2016, TypeScript finally added support for downlevel transpilation of async and await keywords for ES3 and ES5 targets. To give this new feature a try, I decided to convert the Angular Tour of Heroes tutorial to use async and await.