使用 ngClass 添加样式时出现样式错误

styling error when added styles using ngClass

当我只使用 class 名称如错误和信息时 css 有效

示例:https://stackblitz.com/edit/github-i4uqtt-zrz3jb(使用 Angular 最新版本)

但是当我重命名 css class 并添加更多样式时,例如下面的示例 css 和 [ngClass] 不再起作用。有什么想法吗? #HTML

<div fxLayout="row" fxLayoutAlign="space-between">
  <div fxLayout="column" fxFlex="0 0 7%">
    <mat-icon 
    [ngClass]="password.hasError('mininum') ? 'error-check-outline' : 'info-check-outline'">
    check_circle_outline </mat-icon>
  </div>
  <div fxLayout="column" fxFlex="0 0 100%">
    <span 
    [ngClass]="password.hasError('mininum') ? 'text-info-error' : 'text-info'">
    8 characters mininum</span>
  </div>
</div>

#ts

validateMinimumPassword: ValidatorFn = (control: AbstractControl) => {
  if (control.value.length < 8) {
    return { minimum: true };
  }
  return null;
};

#CSS

.text-info {
  font-family: Inter;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  color: #4caf50;
  font-family: Manrope;
  margin-top: 2.5px;
}

.text-info-error {
  font-family: Inter;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  color: #DDD;
  font-family: Manrope;
  margin-top: 2.5px;
}

.error-check-outline {
  transform: scale(.74);
  color: #DDD;
}

.info-check-outline {
  transform: scale(.74);
  color: #4caf50;
}

您必须将 ngClass 条件包装在 {} 中,同时更改语法

例如:

[ngClass]="{'error-check-outline': password.hasError('minimum'), 'info-check-outline' : !password.hasError('minimum'
)}"

你可以根据条件return写一个方法给class

setClass(type) {
  if (type == 'minimum') {
    return 'class-one';
  } else if (type == 'maxmimum') {
    return 'class-two';
  }
}

然后在 HTML 中使用此方法,如下所示

<div [ngClass]="setClass('minimum')"><div>

使用这种方式你可以清理你的HTML

如果您更正拼写错误 mininum,一切都应该有效。它的最小值

工作示例:https://stackblitz.com/edit/so-68358839


更新:为什么它是绿色的

你有表达式 "password.hasError('mininum') ? 'text-info-error' : 'text-info'"

ternary(conditional) operator 语法就像,

condition ? exprIfTrue : exprIfFalse

你给了 password.hasError('mininum'),因为它有错字 returns null,即 falsey。所以现在左边的表达式是错误的, .text-info 将被选中。由于那个样式使颜色变成绿色,所以它会变成绿色。