简体   繁体   中英

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

How to conditionaly add an attribute in the template after checking if a variable is defined? I want to add an attribute with the variable value to an HTML tag, but this variable might not exist. How can I check that?

In the following example, myVariable might not be defined in the component and it will throw an error:

<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>

Normally the attribute should disappear when the binding value is null

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

You forget the [] around your attribute name to make it bindable: <i class="fa fa-file-excel-o" [title]="myVariable? myVariable: ''"></i>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM