Angular 模板中的 $any() 类型转换函数

Nit*_*ish 16 angular

如何在 Angular 模板中使用$any()类型转换函数?

在角度文档中 - https://angular.io/guide/template-typecheck#disabling-type-checking-using-any 已经给出了一些描述和示例,但仍然不清楚。

有一个例子是这样的——

<p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
Run Code Online (Sandbox Code Playgroud)

zma*_*mag 22

只需用 包裹一个变量$any()。不需要额外的代码。

组件.ts

export class AppComponent {
  val = { name: 'foobar' }
}
Run Code Online (Sandbox Code Playgroud)

组件.html

<p>
  {{ $any(val).name }}
</p>
Run Code Online (Sandbox Code Playgroud)

堆栈闪电战:https://stackblitz.com/edit/angular-qivjym


And*_*ico 9

接受的答案给出的例子并没有显示背后的真正原因$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>
Run Code Online (Sandbox Code Playgroud)

*ts

obj = { prop1: 'hehe'};

ngOnInit() {
  (this.obj as any).newProp = 'lol';
}
Run Code Online (Sandbox Code Playgroud)

https://stackblitz.com/edit/angular-ivy-aoufm?file=src%2Fapp%2Fapp.component.html