Reputation:
I have three button within a div (each has a different color) with opacity: 0.1
.
When I click one of them, I'd change it's opacity to 1 and this is my problem.
How I check if an element has a specific class? I was thinking to use ngClass.
Upvotes: 0
Views: 765
Reputation: 28708
You can use ngClass. For 3 buttons:
<button [ngClass]="{'semi': active !== 1, 'opaque': active === 1}" (click)="active = 1">Button 1</button>
<button [ngClass]="{'semi': active !== 2, 'opaque': active === 2}" (click)="active = 2">Button 2</button>
<button [ngClass]="{'semi': active !== 3, 'opaque': active === 3}" (click)="active = 3">Button 3</button>
or for a more general case:
<ng-container *ngFor="let button of [1,2,3,4]; let i = index">
<button [ngClass]="{'semi': active !== i + 1, 'opaque': active === i + 1}" (click)="active = i + 1">Button {{i + 1}}</button>
</ng-container>
Upvotes: 0
Reputation: 4207
The better way to do it is creating a very simple custom directive :
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appOpacity]'
})
export class OpacityDirective {
@HostBinding('class.opacity-1') isClicked = false;
@HostListener('click') toggleOpen() {
this.isOpen = !this.isOpen;
}
}
It toggle the opacity-1 class on click. And then attach this directive on your element :
<div>
<button #appOpacity> Click here</button>
</div>
Upvotes: 1
Reputation: 21377
try this :
<button (click)="opacityClass=true" [ngClass]="{'active':opacityClass}">
</button>
.active{
opacity:1;
}
Upvotes: 0