Strider
Strider

Reputation: 3749

Adding class dynamically from template

I am trying to add a class to an Item depending on whether or not this same class exist in another Item.

In the following code, I used data binding with classList but it didn't work:

<ion-item #firstItem>
   <ion-label>My label</ion-label>
   <ion-input type="text" formControlName="myInput"></ion-input>
</ion-item>
<!-- ....... -->
<ion-item [class.myClass]="firstItem.classList.contains('myClass')">
  <ion-input value="myValue" readonly></ion-input>
</ion-item>

My goal is whenever the firstItem has the class myClass, it will be added automatically to the second item, but all I've got is an undefined classList

Do you have any idea why my previous code isn't working?

Thanks

Upvotes: 3

Views: 61

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73741

The problem is that the #firstItem variable refers to the ion-item component instance, not to the underlying HTML element. The component class does not have the classList property.

You can access the ion-item HTML element in code with the ViewChild read option, and check if the class is defined for that element in a method:

@ViewChild("firstItem", { read: ElementRef }) firstItemRef: ElementRef;

public firstItemHasClass(className: string): boolean {
  return this.firstItemRef.nativeElement.classList.contains(className);
}

The method is then called in the template:

<ion-item [class.myClass]="firstItemHasClass('myClass')">

See this stackblitz for a demo.

Upvotes: 2

Related Questions