mat-form-field required字段显示红色星号,即使在Angular中没有错误 &g



我面临的问题是,即使没有错误,mat-form-field也需要星号。如果没有错误,我想显示蓝色星号。我花了很多时间,但还是没有弄明白。如果有人知道什么是错的,请让我知道。谢谢你

<mat-form-field appearance="outline" class="input-field-large input-normal-wide" matInput>
<mat-label>Name</mat-label>
<input
(input)="onNameChange()"
formControlName="name"
type="text"
autocomplete="off"
matInput
maxlength="50"
required="required"
/>
<mat-icon
*ngIf="form.hasError('required', 'name') && isNameSubmitted"
class="mdi mdi-24px mdi-alert-circle"
matSuffix
>
</mat-icon>
<mat-error *ngIf="form.hasError('required', 'name') && isNameSubmitted">
<span>{{ "This field is mandatory" | translate }}</span>
</mat-error>
<mat-error *ngIf="form.hasError('maxlength', 'name') && isNameSubmitted">
<span>{{ "Maximum 50 charachers are allowed" | translate }}</span>
</mat-error>
</mat-form-field>

可以这样做:

::ng-deep .mat-form-field.mat-focused {
.mat-form-field-required-marker {
color: blue;
}
}
::ng-deep .mat-form-field.mat-form-field-invalid {
.mat-form-field-required-marker {
color: red;
}
}

如果你想改变"*"的颜色,将这个。css添加到你的"style .css"(不在component.css中)

.mat-focused .mat-form-field-required-marker
{
color:blue
}
.ng-invalid.ng-touched.mat-focused .mat-form-field-required-marker
{
color:red
}

只想隐藏"*"您可以使用

[required]="form.hasError('required','name')?true:null"

参见stackblitz

因为你正在使用formControlName指令的表单字段,我猜你有一个formGroup,如果你只是想确保输入有一个值,不要在模板上直接使用required,而是在组件的.ts文件中使用Validators

例如:

public myFormGroup: FormGroup = new FormGroup({
name: new FormControl('', Validators.required)
})

在FormControl构造函数中,你可以传递一个验证器函数或一个验证器函数数组作为第二个参数。所需的函数就是其中之一,其他预定义的验证器有:

  • max
  • min
  • 过的非null的
  • 模式(用于正则表达式验证)

如果需要,也可以定义自定义函数

相关内容