angular模板語法注意事項

模板引用變量也能夠用 ref- 前綴代替 #。 下面的例子中就用把 fax 變量聲明成了 ref-fax 而不是 #fax。javascript

<input ref-fax placeholder="fax number">
<button (click)="callFax(fax.value)">Fax</button>

Angular 的安全導航操做符 (?.) 是一種流暢而便利的方式,用來保護出如今屬性路徑中 null 和 undefined 值。 下例中,當 currentHero 爲空時,保護視圖渲染器,讓它免於失敗。java

The current hero's name is {{currentHero?.name}}

在 TypeScript 2.0 中,你可使用 --strictNullChecks 標誌強制開啓嚴格空值檢查。angular不會默認開啓typescript

<div *ngIf="hero">
  The hero's name is {{hero!.name}}
</div>

在 Angular 編譯器把你的模板轉換成 TypeScript 代碼時,這個操做符會防止 TypeScript 報告 "hero.name 可能爲 null 或 undefined"的錯誤。安全

有時候,綁定表達式可能會報類型錯誤,而且它不能或很難指定類型。要消除這種報錯,你可使用 $any 轉換函數來把表達式轉換成 any 類型。函數

<div>
  The hero's marker is {{$any(hero).marker}}
</div>

在這個例子中,當 Angular 編譯器把模板轉換成 TypeScript 代碼時,$any 表達式能夠防止 TypeScript 編譯器報錯說 marker 不是 Hero 接口的成員。this

$any 轉換函數能夠和 this 聯合使用,以便訪問組件中未聲明過的成員。code

<div>
  Undeclared members is {{$any(this).member}}
</div>

$any 轉換函數能夠在綁定表達式中任何能夠進行方法調用的地方使用。接口

相關文章
相關標籤/搜索