簡體   English   中英

使用Angular 4切換按鈕的類

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM