【问题标题】:Angular Class BindingAngular 类绑定
【发布时间】:2020-03-29 02:01:04
【问题描述】:

我有一个使用类绑定的代码。单击按钮时,字体颜色应根据 textrun 的值更改。 textrun 在 true 和 false 之间变化。如果为 true,它应该以红色显示文本,否则以绿色显示。

TS 文件

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  textrun=true;
  messageClasses={
    "text-success": !this.textrun,
    "text-error": this.textrun,
    "text-info": !this.textrun

    }

  changetrue(){
  this.textrun=false;
  console.log("done");
}
}

HTML 文件

 <h2 [ngClass]="messageClasses">hai</h2>
  <button (click)="changetrue()">click</button>

css 文件

.text-success{
  color:green;
}
.text-error{
  color:red;
}
.text-info{
font-style: italic;
}

编辑:如果要应用多个条件,我需要相同的代码才能工作。

【问题讨论】:

    标签: angular


    【解决方案1】:

    试试这样:

    <h2 [ngClass]="textrun ? 'text-error':'text-success'">hai</h2>
    

    或者,

    <h2 [ngClass]="{'text-error': textrun, 'text-success': !textrun }">hai</h2>
    

    Demo

    【讨论】:

    • 谢谢@Adrita。确实可以这样写。它有效。我试过了。但我不明白为什么上面的代码不起作用。对此有何建议?
    • @nXn 您尝试的语法不正确。我在演示中添加了另一种方法
    • 谢谢。请使用 Demo 中的答案更新答案,以便其他人也可以使用该信息。那行得通。感谢您的支持。
    【解决方案2】:

    您可以使用以下任何一种方法


    方法一:

    <h2 [ngClass]="{'text-error': textrun', 'text-success': !textrun }">hai</h2>
    

    方法二:

    <h2 [ngClass]="textrun ? 'text-error':'text-success'">hai</h2>
    

    方法3:

    <h2 [ngClass]="{true:'text-error',false:'text-success'}[textrun]">hai</h2>
    

    【讨论】:

    • 谢谢@Surjeet。但是如果我有三个条件可以申请。就像我也需要字体是斜体一样,我该如何应用类绑定?
    • 谢谢。我得到了它。感谢您的支持。
    • 最后一种方法是ninjs风格?‍??
    • ? @MuhammedAlbarmavi
    【解决方案3】:

    它不起作用,因为您在属性上引用了this.textrun

    通常在组件初始化时不可用:

    试试:

    textrun = true;
    
    messageClasses;
    
    ngOnInit() {
       this.messageClasses = {
        "text-success": !this.textrun,
        "text-error": this.textrun,
        "text-info": !this.textrun
       }
    }
    
    onClick() {
      this.textrun = !this.textrun;
      this.messageClasses = {
        "text-success": !this.textrun,
        "text-error": this.textrun,
        "text-info": !this.textrun
      }
    }
    

    ngOnInit(),所有属性都应该被声明和初始化。

    【讨论】:

    • 简要说明什么不起作用会比“不起作用”更有帮助
    • 在那之后你能记录这个吗?
    • 我做了你提到的改变,按钮点击颜色没有改变
    【解决方案4】:

    这不起作用,因为在类实例化期间,messageClasses 仅加载一次

    将您的 html 更改为:

    <h2 [ngClass]="{
      "text-success text-info": !textrun,
      "text-error": textrun
      }">
      hai
    </h2>
    <button (click)="changetrue()">click</button>
    

    并从您的班级中删除您的 messageClasses 变量

    【讨论】:

    • 是的。谢谢你。我明白了。
    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2019-12-27
    • 2016-03-29
    相关资源
    最近更新 更多