3

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

1 Answer 1

2

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.

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.