我有如下模板:
<form class="form" [formGroup]="configWeightage">
<div class="example-container">
Enter value in between 0 to 100 <mat-form-field>
<input
matInput
type="number"
min="0"
max="100"
class="example-right-align"
[formControlName]="weightageValue"
id="weightage"
required
/>
</mat-form-field>
<mat-error *ngIf="weightageValue.hasError('min(0)')" style="color: red"
>Please enter greater than 0</mat-error
>
<mat-error *ngIf="weightageValue.hasError('max(100)')" style="color: red"
>Please enter less than 100</mat-error
>
</div>
</form>
這是類檔案
import { Component } from '@angular/core';
import { FormBuilder,FormGroup, Validators,FormControl } from '@angular/forms';
/** @title Form field with prefix & suffix */
@Component({
selector: 'form-field-prefix-suffix-example',
templateUrl: 'form-field-prefix-suffix-example.html',
styleUrls: ['form-field-prefix-suffix-example.css'],
})
export class FormFieldPrefixSuffixExample {
configWeightage:FormGroup;
formBuilder : FormBuilder;
weightageValueControl = new FormControl(['',Validators.required,Validators.min(0),Validators.max(100)]);
hide = true;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.configWeightage = this.formBuilder.group(
{
'weightageValue' :this.weightageValueControl
}
)
}
}
當值不在 0 到 100 之間時,我應該會觸發錯誤
但不會觸發任何驗證訊息
這是相同的堆疊 bliz 代碼,以便您可以自己運行和修復。
https://stackblitz.com/edit/angular-mat-form-field-dq8ntd?file=app/form-field-prefix-suffix-example.html
uj5u.com熱心網友回復:
您應該在 Stackblitz 中修復一些錯誤和拼寫錯誤:
從中洗掉括號
[formControlName]洗掉
min和max屬性,<input>因為您已經使用它們指定了它們validators<mat-error>向內移動<mat-form-field>對于錯誤情況,您應該使用
formGroupName.get('FormControlName').hasError('validatorName')style="color: red"從中洗掉<mat-error>,這已經是錯誤訊息的默認樣式。修正錯字
this.formBuilder.group為this.fb.group這是修復上述錯誤后的Stackblitz 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/450225.html
標籤:javascript html 有角度的 打字稿 角7
下一篇:使用螢屏鍵盤提交表單
