![](/img/trans.png)
[英]Angular: Toggle active class on only button the current clicked button (not using *ngFor)
[英]Toggle Class of the button using Angular 4
我正在尝试启用/禁用按钮
App.component.html:根组件在更改时触发并设置初始值。
<!--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:由根组件组成,由更改功能和post对象组成
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.ts
<button class="waves-effect waves-light btn" [class.enabled]="isSelected" [class.disabled]= "!isSelected" (click)="onClick" >Click to {{isSelected}}</button>
favorite.component.ts:由onclick组成,用于切换类并发出结果
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() { } }
该按钮未切换。 没有类更改,并且发射器也不会发出任何结果。
将(click)="onClick"
更改为(click)="onClick()"
在favorite.component.ts中
这是正确的答案。
感谢@Daniel指出。
从描述中还不清楚onClick
函数是否完全被触发,但是对于调整Angular中的类设置,直接像[class.whatever]="expression"
这样的类对我也不起作用,而是我成功使用了这种形式:
<button [ngClass]="{ 'enabled': isSelected, 'disabled': !isSelected }">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.