Search code examples
angulartypescriptdirectivetypechecking

How to type check Angular Directive input assignment types in templates?


I am using Angular 9 and have following Angular directive :

export type MyDirectiveValue = "foo"|"bar"; 
@Directive({
    selector: '[myDirective]'
})
export class MyDirective implements OnInit {
    @Input("myDirective") value: MyDirectiveValue;
    
    ngOnInit() {
        console.log(this.value);
    }
}

When I use it in my template :

<div *myDirective="'invalid-value'">Hello</div>

I would have expected Ivy to detect that invalid-value is not assignable to type MyDirectiveValue but it's not, I can freely assign any value without getting any template compilation failure.

Any idea ?


Solution

  • Please check out documentation: https://angular.io/guide/template-typecheck

    Especially this part:

    Strict mode

    Strict mode is a superset of full mode, and is accessed by setting the strictTemplates flag to true. This flag supersedes the fullTemplateTypeCheck flag. In strict mode, Angular version 9 adds checks that go beyond the version 8 type-checker. Note that strict mode is only available if using Ivy.