Conditionally switch class in angular 2

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

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

header.html application

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

How to do this using only angular since the div and button are in two different components? Please help, I'm new to angular !!!

+5
source share
3 answers

You can use EventEmitter .

header.html application

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

application header.ts

 @Output() _clickEvent:EventEmitter<any>=new EventEmitter(); constructor(){ } ngOnInit(){ } emitClick($event){ this.clickEvent.emit() } 

application-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 must declare the active variable in your app-component.ts and initialize it before Boolean. Each click will cause an active switch between true and false. A class named "someClassName" will be added by ngClass whenever the it true variable is active.

+2
source

You can associate your object with the [ngClass] directive:

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

To exchange data between components, see this answer: fooobar.com/questions/1270385 / ...

+5
source

You can create a shared service and save the variable as public, for example:

 @Injectable() export class DataService{ foo:string; } 

Then use the variable in both components as a shared variable, for example:

 @Component({...}) export class FooComponent{ constructor(private dataService:DataService){} foo():void{ console.log(this.dataService.foo); } } 
+2
source

Source: https://habr.com/ru/post/1270384/


All Articles