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!!!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With