【问题标题】:Changing the input's text color depending on it's value, Angular根据输入的值 Angular 更改输入的文本颜色
【发布时间】:2019-09-17 04:21:25
【问题描述】:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div class="form-group">
  <label class="col-md-4">What is the capital city of Italy?
  </label>
  <input type="text" class="form-control" formControlName="first_question" #first_question />
</div>

所以,我想让输入颜色为红色,除非用户输入正确的答案是罗马?有任何想法吗?我试过了,但没有用:

placeholder="Type" [style.color]="Type === 'rome' ? 'red' : 'green'"

【问题讨论】:

  • 显示 TS 代码
  • placeholder="Type" [style.red]="Type === 'rome'" [style.green]="Type !== 'rome'" 是一种简单的方法

标签: css angular angular7


【解决方案1】:

如果您使用的是Reactive Forms,请使用:

this.your_formgroup.get('first_question').value

所以 HTML 代码将是:

<div [formGroup]="your_formgroup">
    <mat-form-field>
        <input matInput placeholder="Input" formControlName="first_question" [style.color]="this.your_formgroup.get('first_question').value === 'rome' ? 'red' : 'green'">
    </mat-form-field>
</div>

没有表单组:

  • 已删除formControlName

  • 已使用.toLowerCase(),因为RomerOmE 是有效输入:)

HTML 代码:

<mat-form-field>
        <input matInput placeholder="Input" [(ngModel)]="first_question" [style.color]="first_question.toLowerCase() === 'rome' ? 'red' : 'green'">
</mat-form-field>

TS:

first_question: any = "";

WORKING_DEMO

【讨论】:

    【解决方案2】:

    首先你需要在 TS 中声明一个变量。

        TheCapitalOfItaly:string = '';
    

    然后,在 html 中:

    [(ngModel)]=="TheCapitalOfItaly" [style.color]="TheCapitalOfItaly=== 'rome' ? 'green' : 'red'"
    

    【讨论】:

    • 输入在 test.component.html 上,所以我必须把声明的变量放在 test.component.ts 中,对吧?
    • 是的,当然要确保在“test.component.ts” URLS中注册了“test.component.html”
    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 2013-12-07
    • 2022-01-12
    • 2020-09-08
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多