Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally toggle class in angular 2

Tags:

html

angular

I need to toggle a class "active" on in app-component whenever a button in "app-header" component is clicked. Here is my app-component.html,

<div class="off-canvas">
    <app-header><app-header>
    <app-home></app-home>
    <app-footer></app-footer>
</div>

app-header.html

<div>
<!--Some code-->
<button></button>
</div>

How can I do this using only angular since the div and button are in 2 different components????please help I am new to angular!!!

like image 231
Mr.Gaja Avatar asked Jul 31 '17 09:07

Mr.Gaja


2 Answers

You can bind your object to the [ngClass] directive:

<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">

To share data between components, see this answer: https://stackoverflow.com/a/45371025/1791913

like image 72
Faisal Avatar answered Nov 06 '22 07:11

Faisal


You can use EventEmitter.

app-header.html

<div>
<!--Some code-->
<button (click)="emitClick()"></button>
</div>

app-header.ts

@Output() _clickEvent:EventEmitter<any>=new EventEmitter();

constructor(){
}
ngOnInit(){
}
emitClick($event){
  this.clickEvent.emit()
}

app-component.html

<div class="off-canvas" [ngClass]="{'someClassName':active}">
    <app-header (_clickEvent)="toggleActive($event)"><app-header>
    <app-home></app-home>
    <app-footer></app-footer>
</div>

app-component.ts

  active:boolean=false;    
    constructor(){
    }
    ngOnInit(){
    }
   toggleActive($event){
    // Insert click event handling here
   }

You should declare active variable in your app-component.ts and initialized it to Boolean. Every click will cause the active to toggle between true and false. A class named 'someClassName' will be added by the ngClass whenever the 'active' variable it true.

like image 30
Gili Yaniv Avatar answered Nov 06 '22 08:11

Gili Yaniv