-1

I have a Component, where we want to Input an HTML attribute.

However if No value is provided for input, I do Not want even display the attribute in html. How can this be done? Right now it shows as "".

export class ProductComponent implements OnInit {

  @Input dataQA: string;

HTML:

<div class="productTitle"
    data-qa="dataQA"
>

Note: I want to keep the Whole Div, just exclude the attribute within the div. I may have multiple attributes future within the div, so looking for efficient solution.

2 Answers2

1

You can use *ngIf="<condition>" for that

IE: <div class="productTitle" data-qa="dataQA" *ngIf="dataQa">

To apply an attribute dynamically, you can do something similar by using attribute bindings:

IE: <p [attr.dataQA]="something ? null : ''">

Explanation: null means attribute will not be applied. '' (an empty string) applies the attribute without value (ie dataQA opposed to dataQA="some value")

For a string in your example, it would be

<p [attr.test]="something ? something : null">

https://angular.io/api/common/NgIf

https://angular.io/guide/attribute-binding

Here's an example: https://stackblitz.com/edit/angular-ivy-jwvwhu?file=src%2Fapp%2Fapp.component.html

mwilson
  • 12,295
  • 7
  • 55
  • 95
-1

You can use ngIf for adding a conditional check. For your requirement you can add two separate HTML elements, one with attribute and one without attribute. Then applying condition on the elements.

Try this:

<div class="productTitle" [attr.data-qa]="dataQA || null"></div>
  • I want to keep the Whole Div, just exclude the attribute within the div. I may have multiple attributes future within the div, so looking for efficient solution. –  Nov 20 '20 at 18:09
  • Updated with attribute binding. You can remove the value of the attribute using that. But you can't remove the attribute. – Jins Thomas Shaji Nov 20 '20 at 18:22