How to use the $any() type cast function in Angular template?
In angular documentation- https://angular.io/guide/template-typecheck#disabling-type-checking-using-any some description and examples have been given but still, it is not clear.
There one example is given like this-
<p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
Simply wrap a variable with $any()
. No additional code required.
component.ts
export class AppComponent {
val = { name: 'foobar' }
}
component.html
<p>
{{ $any(val).name }}
</p>
stackblitz: https://stackblitz.com/edit/angular-qivjym
The example given by the accepted answer does not show the real reason behind $any
<p> {{obj.prop1}}</p>
<!--
This will throw an error without $any() because newProp is not part of typeof obj.
<p> {{obj.newProp}}</p>
-->
<p> {{$any(obj).newProp}}</p>
*ts
obj = { prop1: 'hehe'};
ngOnInit() {
(this.obj as any).newProp = 'lol';
}
https://stackblitz.com/edit/angular-ivy-aofufm?file=src%2Fapp%2Fapp.component.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With