Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$any() type cast function in Angular template

Tags:

angular

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>
like image 823
Nitish Avatar asked Mar 04 '23 18:03

Nitish


2 Answers

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

like image 194
zmag Avatar answered Mar 15 '23 21:03

zmag


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

like image 31
Andre Elrico Avatar answered Mar 15 '23 22:03

Andre Elrico