0

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>
wilbi
  • 225
  • 2
  • 14
  • 1
    Does this answer your question? [How to add conditional attribute in Angular 2?](https://stackoverflow.com/questions/36745734/how-to-add-conditional-attribute-in-angular-2) – Nick Parsons Dec 04 '20 at 11:30
  • You simply forgot to add the `[]` to the attribute for Angular binding. – Ploppy Dec 04 '20 at 11:33
  • That doesn't solve the problem. If the variable is not declared in the component, I am still getting "Identifier 'myVariable' is not defined. The component declaration, template variable declarations, and element references do not contain such a member" – wilbi Dec 04 '20 at 12:23
  • https://ibb.co/RB640c3 – wilbi Dec 04 '20 at 12:26

2 Answers2

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

Pieterjan
  • 2,738
  • 4
  • 28
  • 55
  • "Identifier 'myVariable' is not defined. The component declaration, template variable declarations, and element references do not contain such a member" – wilbi Dec 04 '20 at 13:06
  • Added stackblitz – Pieterjan Dec 04 '20 at 15:28
  • Yes but I repeat. You DEFINED the myVariable in the component. Remove the myVariable: string = null; from the component and try again. – wilbi Dec 04 '20 at 16:50
0

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

Mathieu Seiler
  • 726
  • 8
  • 13
  • 1
    That doesn't solve the problem. If the variable is not declared in the component, I am still getting "Identifier 'myVariable' is not defined. The component declaration, template variable declarations, and element references do not contain such a member" – wilbi Dec 04 '20 at 12:22
  • 1
    By design, the property should at least be declared in your component controller with public visibility. This is typescript way of coding. – Mathieu Seiler Dec 04 '20 at 12:52