簡體   English   中英

Angular:檢查是否定義了變量后,如何有條件地在模板中添加屬性?

[英]Angular: How to conditionaly add an attribute in the template after checking if a variable is defined?

檢查是否定義了變量后,如何有條件地在模板中添加屬性? 我想將具有變量值的屬性添加到 HTML 標記,但此變量可能不存在。 我該如何檢查?

在以下示例中,myVariable 可能未在組件中定義,它會引發錯誤:

<i class="fa fa-file-excel-o" title="myVariable ? myVariable : null"></i>
<i class="fa fa-file-excel-o" [attr.title]="myVariable ? myVariable : null"></i>

通常當綁定值為null時該屬性應該消失

https://stackblitz.com/edit/angular-ivy-2rr8hk

您忘記了屬性名稱周圍的 [] 以使其可綁定: <i class="fa fa-file-excel-o" [title]="myVariable? myVariable: ''"></i>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM