2

Is it possible in Angular to only render an element attribute if it is defined?

If for example I have a button component

export class ButtonComponent {
  /** The name id to be given to the button */
  @Input() id: string;
  /** The name to be given to the button */
  @Input() name: string;
}

with a template of

<button 
        [id]="id"
        [name]="name"
        >
    <ng-content></ng-content>
</button>

and if I pass it an id but not a name it renders a name attribute with a value of undefined.

<button _ngcontent-c1="" id="login" name="undefined">
    Login
</button>

Is it possible to not render the name attribute at all if the name input is not supplied like below?

<button _ngcontent-c1="" id="login">
    Login
</button>
0

1 Answer 1

3

In case of attribute binding angular won't render attribute if we pass null or undefined to it. So your solution could look like:

[attr.name]="name"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.