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.
Posts about Angular
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
In an Angular application, I wanted to test a functionality that depends on the current time (by calling Date.now()). Jasmine has great built-in support for spying on methods, so my first approach was to create a spy for Date.now() 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.
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.
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.
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.
Angular pipes are a useful tool for formatting values for display. However, they may not work as expected for composite objects.
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.
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.
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.
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).
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.
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.
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.
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".
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.
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.
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.
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.
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".
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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 NgZone.run() helped. However, it bothered me why this was only necessary in this single instance.
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.
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.
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.
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.
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?
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.
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.