Just as TypeScript catches type errors in your code, Angular checks the expressions and bindings within the templates of your application and can report any type errors it finds. Angular currently has three modes of doing this, depending on the value of the fullTemplateTypeCheck and strictTemplates flags in your tsconfig.json file. I will focus on the most interesting option, which is strictTemplates.
Let's take this Book interface as an example:
interface Book { name: string; author: { firstName: string; lastName: string; }; }
We display a list of books: Book[] like this in our template:
<h2>{{config.title}}</h2> <div *ngFor="let book of books"> <span>Name: {{book.name}}</span> <app-author-name [name]="book.author.lastName"></app-author-name> </div>
And our (really dumb) AuthorNameComponent, that takes an @Input() name: string; :
<span>Author: {{name}}</span>
1) Basic mode: { strictTemplates: false, fullTemplateTypeCheck: false }
In the most basic type-checking mode, Angular validates only top-level expressions in a template.
In the previous example, the compiler checks the following:
- config is a property on the component class with a title property
- books is a property on the component class
What it does not check:
- if the value of book.author.lastName is assignable to the name input of the <app-author-name> component
- the type of book variable in the *ngFor loop (here, book: any)
- the types of #refs, the results of pipes, or the type of $event in event bindings.
2) Strict mode: { strictTemplates: true }
Angular maintains the behavior of the fullTemplateTypeCheck flag, and introduces a "strict mode". Strict mode is a superset of full mode, and is accessed by setting the strictTemplates flag to true.
In addition to the full mode behavior, Angular does the following:
- Checks that component/directive bindings are assignable to their @Input()s:
In our example, book.author.lastName must be of type string to be valid, otherwise the compiler will throw an error.
- Checks *ngFor templates:
With this option enabled, the book variable in our *ngFor loop will have a Book type (book: Book). It ensures that we can only use known properties inside the loop.
For example:
<span>{{book.title}}</span>
will give the following error:
Property' title' does not exist on type Book.
- Infers the correct type of $event in component/directive, DOM, and animation event bindings.
- ... And other checks :)
So in conclusion, strictTemplates is a really powerful feature (introduced in Angular 9) that I strongly encourage you to use in your Angular projects, as it will check templates types for you and prevent you from various bugs!