0

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.

5
  • when you click a button, you want the button you click to change to opacity: 1? Commented Nov 6, 2017 at 9:37
  • 4
    You should share some code to make the problem clearer. Commented Nov 6, 2017 at 9:37
  • @mast3rd3mon yes, i added a css class called 'active' with opacity: 1 Commented Nov 6, 2017 at 9:39
  • 1
    could you add your html code and ts code to your question? Commented Nov 6, 2017 at 9:40
  • I'm sorry guys, i should have add the html code, my apologies. Commented Nov 6, 2017 at 10:10

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. I'd have shared the code, my apologies.
0

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>

DEMO

Comments

0

try this :

   <button (click)="opacityClass=true" [ngClass]="{'active':opacityClass}">
   </button>

.active{
   opacity:1;
  }

1 Comment

I'm sorry man but i was busy and i don't see your answer. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.