【问题标题】:Toggle Class of the button using Angular 4使用 Angular 4 切换按钮的类
【发布时间】:2018-02-10 21:02:07
【问题描述】:

我正在尝试启用/禁用按钮

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 :由根组件组成,包含更改功能和发布对象

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() {
  }

}

按钮没有切换。没有类变化,发射器也不会发出任何结果。

【问题讨论】:

  • 你试过 this.change.emit();因为 emit 是一个函数?
  • 在您的favorite.component.ts 中将(click)="onClick" 更改为(click)="onClick()"
  • @bryan60 是的,请检查编辑
  • console.log("clicked") 怎么样,是不是被触发了;以及按钮内容{{isSelected}},是否改变了?

标签: javascript angular


【解决方案1】:

改变 (click)="onClick"(click)="onClick()"

在 favorite.component.ts 中

这是正确答案。

感谢@Daniel 指出。

【讨论】:

    【解决方案2】:

    从描述中不清楚onClick函数是否被触发,但至于在Angular中调整类直接设置它像[class.whatever]="expression"对我也不起作用,相反我成功地使用了这个表单:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      相关资源
      最近更新 更多