mat-form-field 总是显示所需的红色?

mat-form-field always show required red color?

有什么方法可以让 mat-form-fieldrequired="true" 时始终显示红色,即使我从未将焦点放在它上面或我触摸过它?

<mat-form-field color="accent">
  <input matInput placeholder="ID is required" required="true [(ngModel)]="uniqueID">
</mat-form-field>

我只想显示错误的红色,但从一开始,在我触摸输入之前。

怎么可能?

如果您愿意使用响应式表单...使用 ngAfterViewInit,您可以通过编程方式将字段标记为已触及以强制错误。

  • 不幸的是,我不熟悉如何通过 模板驱动的表单。

    setTimeout(() => {
            this.yourForm.controls['yourControl'].markAsTouched();
          }, 0);
    

修订

基于我最初的回答,以及 Abhishek 对我的回答的扩展,以再次强调您可以使用反应式表单来做到这一点...我也想提供模板驱动的表单场景。

  • 这里的共同主题是,无论您使用反应式表单还是模板驱动表单,您都需要以编程方式标记 按触摸输入...
  • 在模板驱动的表单中,您还需要做 通过模板引用相同,以便您可以调用控件上的 markAsTouched() 方法 你的 ngOnInit 生命周期钩子。

设置 id 的模板引用并通过输入上的 #id="ngModel" 将其绑定到 ngModel...您还需要通过 name="id" 在 id 的输入上分配一个名称,这是一个绑定到 ngModel 的要求。

<mat-form-field color="accent">
    <input matInput placeholder="ID is required" required="true" [(ngModel)]="uniqueID" name="id" #id="ngModel">
</mat-form-field>

<div *ngIf="id.invalid && (id.dirty || id.touched)">
    <mat-error *ngIf="id.errors.required">
        ID is <strong>required</strong>
    </mat-error>
</div>

<pre>id.errors: {{id.errors | json}}</pre>

从这里开始,您需要在组件中使用 @ViewChild 来获取对 #id 的引用,并通过 ngOnInit 生命周期挂钩在控件上调用 markAsTouched()

import {Component, OnInit, ViewChild} from '@angular/core';

@ViewChild('id') _id : any

ngOnInit(){
  this._id.control.markAsTouched();
}

以下演示以现有 angular material 反应形式显示了所需的案例。

应用演示:
https://stackblitz.com/edit/example-angular-material-reactive-form-2rksrw?file=app/app.component.ts

方法:

  • ngOnInit中,我们可以从表单中获取输入元素,可以修改为
    this.formGroup.get('name').markAsTouched();
  • 我们也可以利用 from 输入的 touched 属性 作为
    this.formGroup.get('name').touched = true;,但这会产生错误 Cannot assign to 'touched' because it is a constant or a read-only property.
    但在 stackblitz 演示中,您可以看到它的工作原理,因为我们也可以看到与 this.formGroup.get('name').touched = false; 的区别。

formGroup 是在演示表单中按以下方式创建的:

 this.formGroup = this.formBuilder.group({
      'email': [null, [Validators.required, Validators.pattern(emailregex)]],
      'name': [null, Validators.required],
      'password': [null, [Validators.required, this.checkPassword]],
      'description': [null, [Validators.required]],
      'validate': ''
    });

HTML

   <mat-form-field class="floatRight"> <input matInput [formControl]="formfieldControl" placeholder="enter name"[(ngModel)]="strSolrCoreName" Required> 
   </mat-form-field>

.ts 文件

import { FormControl, Validators } from '@angular/forms';

export class abc{
formfieldControl = new FormControl( '', [Validators.required] );
}

您可以使用类似于 docs 中示例的自定义垫标签。

Stackblitz for the example in docs

模板代码:

<mat-form-field>
  <mat-label>ID is required<span style="color: red">&nbsp;*</span></mat-label>
  <input matInput [(ngModel)]="uniqueID">
</mat-form-field>

由于我们通过 mat-label 显示 *,将 required 属性放在输入上会在字段上添加一个额外的 *,因此应将其省略。您可以在组件中处理验证。

更新:

由于 [(ngModel)] 像 Marshal 提到的那样被弃用,您可以删除 [(ngModel)] 并使用 FormControl 的内置 Observable valueChanges 来获取用户输入,如下所示:

.html

<mat-form-field color="accent">
  <input matInput placeholder="ID is required" required [formControl]="formFieldControl">
</mat-form-field>

.ts

formFieldControl: FormControl;

ngOnInit() {
  formFieldControl = new FormControl('', [Validators.required]);
  this.formFieldControl.markAsTouched();
  this.formFieldControl.valueChanges.subscribe(value
      uniqueID = value;
    );
}

原答案:

最简单的解决方案在 Abhishek Kumar 的回答中。这是您示例中所需的全部内容:

.html

<mat-form-field color="accent">
  <input matInput placeholder="ID is required" required [formControl]="formFieldControl" [(ngModel)]="uniqueID">
</mat-form-field>

.ts

formFieldControl: FormControl;

ngOnInit() {
  this.formFieldControl = new FormControl('', [Validators.required]);
  this.formFieldControl.markAsTouched();
}

您还可以设置条件标签颜色或 class 未提供值时。

html

<mat-form-field>
  <mat-label [style.color]='!value ? "red" : "inherit"'>Label</mat-label>
  <input matInput [(ngModel)]='value' required>
</mat-form-field>

Example

如果你想使用class:

html

<mat-form-field>
  <mat-label [class.required]='!value'>Label</mat-label>
  <input matInput [(ngModel)]='value' required>
</mat-form-field>

css (scss)

.required {
    color: red;
    // color: mat-color($warn, 500);
  }