Mr.Gaja
Mr.Gaja

Reputation: 183

Conditionally toggle class in angular 2

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!!!

Upvotes: 8

Views: 11318

Answers (3)

Anas
Anas

Reputation: 991

You can create a common service and store a variable as public, example:

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

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

@Component({...})
export class FooComponent{
    constructor(private dataService:DataService){}

    foo():void{
        console.log(this.dataService.foo);
    }
}

Upvotes: 2

Gili Yaniv
Gili Yaniv

Reputation: 3221

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.

Upvotes: 5

FAISAL
FAISAL

Reputation: 34691

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

Upvotes: 6

Related Questions