简体   繁体   中英

Toggle Class of the button using Angular 4

I am trying to enable /disable button

App.component.html : Root component triggers on change and sets initial value.

 <!--The content below is only a placeholder and can be replaced.--> <div class="container"> <div style="text-align:center"> <h1> {{ title }}! </h1> <favorite [isFavorite]="post.isFavorite" (change)="onFavoriteChange($event)" ></favorite> </div> <h1></h1> <courses></courses> </div> 

app.component.ts : consists of root component consists on change function and post object

 import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Hello User'; post={ title:'Pti', isFavorite:true } onFavoriteChanged(isFav) { console.log("On Favorite Changed",isFav); } } 

Favorite Component

favorite.component.ts

  <button class="waves-effect waves-light btn" [class.enabled]="isSelected" [class.disabled]= "!isSelected" (click)="onClick" >Click to {{isSelected}}</button> 

favorite.component.ts : consists of onclick to toggled the class and emit the result

 import { Component, OnInit, Input, Output ,EventEmitter } from '@angular/core'; @Component({ selector: 'favorite', templateUrl: './favorite.component.html', styleUrls: ['./favorite.component.css'] }) export class FavoriteComponent implements OnInit { @Input('isFavorite') isSelected: boolean; @Output() change=new EventEmitter(); onClick() { console.log("CLicked"); this.isSelected=!this.isSelected; this.change.emit(isSelected); } ngOnInit() { } } 

The button is not toggling. No class change and emitter too does not emit any result.

Change (click)="onClick" to (click)="onClick()"

in favorite.component.ts

This is the correct answer .

Thanks @Daniel for pointing it out.

从描述中还​​不清楚onClick函数是否完全被触发,但是对于调整Angular中的类设置,直接像[class.whatever]="expression"这样的类对我也不起作用,而是我成功使用了这种形式:

<button [ngClass]="{ 'enabled': isSelected, 'disabled': !isSelected }">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM