【问题标题】:How to apply css class based on condition that char length > 128如何根据字符长度> 128的条件应用css类
【发布时间】:2020-01-13 18:23:54
【问题描述】:

这是一个角度应用程序,我想根据变量的字符长度大于 128 个字符的条件应用 css 类。我受到这篇帖子enter link description here 的启发。如下代码 sn-ps 所示,我试图根据 charlen 值在 128 以内或以外的条件动态应用样式。 请我是 Angular 的新手,我不知道许多概念,谢谢你的建议。

template.html

<input [ngClass] = "(charlen <128)?'class1':'class2' />

template.ts

str:String;
charlen:Number;

ngInit () {
 str="this is not 128 char";
 charlen = str.length;
}

template.css

.class1 {
color:red;
}

.class2 {
 color:blue;
}

【问题讨论】:

    标签: css angular typescript ng-class


    【解决方案1】:

    你可以这样做:

    <input [ngClass]="{ 'class1': charlen < 128, 'class2': charlen >= 128 }" />
    

    【讨论】:

    • 你忘记了“{”和“}”
    【解决方案2】:

    使用带有属性绑定的类,我们可以实现上述

    .html

    <input [class] = "(charlen <128)?'class1':'class2'" />
    

    .ts

    str:String;
    charlen:Number;
    
    ngOnInit() {
      this.str= "this is not 128 char";
      this.charlen = this.str.length;
    }
    

    【讨论】:

      【解决方案3】:

      检查此代码

      import { Component, OnInit } from '@angular/core';
      
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
      })
      export class AppComponent implements OnInit  {
        name = 'Angular';
      
        str:String;
      charlen:Number;
      
      ngOnInit () {
       this.str="this is not 128 char";
       this.charlen = this.str.length;
      }
      }
      

      并使用相同的 html 代码,它正在工作。

      查看working demo

      如果您遇到任何问题,请告诉我。

      【讨论】:

        猜你喜欢
        • 2022-08-16
        • 1970-01-01
        • 1970-01-01
        • 2014-08-07
        • 2023-04-11
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 2019-02-19
        相关资源
        最近更新 更多