0

I have a button/img in LI. I want to when clicked change css and text-decoration underline.

Ts file :

onSelect(i: number) {
var element = document.getElementsByClassName('brand')[i];
const elementClass = element.className;

if (elementClass != 'btn brand selected') {
  this.renderer.addClass(element,'selected');
}
else{
  this.renderer.removeClass(element,'selected');
}

}

HTML file :

<li class="nav-item" *ngFor="let brand of brands let i = index">
        <button class="btn brand" id="brand" type="button" data-toggle="showCategory" aria-controls="tabOne"
          data-target="#tabOne" href="#merk1" (click)="getCategories(brand.id); onSelect(i);">
          <img [src]="brand.imageLink" width="100" height="40" [alt]="brand.name" role="button">
        </button>
      </li>
3
  • You want to change style of the button on which you clicked? Commented Aug 4, 2021 at 7:46
  • Yes, i create logic but when i clicked different img not deleted prev underline in img Commented Aug 4, 2021 at 7:49
  • You shouldn't use document.getElementBy ... in angular since you could use ViewChild else you could also just change the value of a varaible in the component and use an [ngClass]="my condition" inside the html Commented Aug 4, 2021 at 7:57

1 Answer 1

1

The simplest solution could be using [ngClass] directive with some logic rather than getting the DOM element and manipulating it.

// declare a variable to which assign the selected brand index
selectedBrand: number;

In template assign the current selected index

<li class="nav-item" *ngFor="let brand of brands let i = index">
    <button class="btn brand" (click)="getCategories(brand.id); selectedBrand=i"> <=== NOTE this
      <img [src]="brand.imageLink" width="100" height="40" [ngClass]="{'selected': selectedBrand === i}"> <=== You can assign any class if the current index and selected index is matched
    </button>
  </li>

Hope this works with you

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help you dont forget to upvote to help others thanks

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.