我是 Angular 的新手,并且陷入了驗證中。
我的問題是我有 4 個選項可供選擇的下拉選單。當用戶選擇一個選項時,我希望輸入欄位以以下方式更改驗證:
如果用戶在下拉選單中選擇選項 1,則我希望在下一個輸入欄位中具有所需的驗證和最大長度 8 個數字。同樣,如果用戶在下拉選單中選擇選項 2。我希望輸入欄位具有所需的驗證和 5 個數字的最大長度。所以我陷入了驗證如何做到這一點。任何幫助和想法將不勝感激##標題##
uj5u.com熱心網友回復:
我建議你使用 ReactiveFormsModule。添加 app.module.ts
@NgModule({
...
imports: [
...
ReactiveFormsModule,
...
]
...
})
export class AppModule { }
在您的組件中yourcomponent.component.ts
maxlenght: number = 10; //default value
insertForm: FormGroup = this.fb.group({
selectType: ['', Validators.required],
otherField: [''],
});
constructor(private fb: FormBuilder) {}
change() {
this.maxlenght = this.insertForm.get('selectType').value || 10;
this.insertForm.get('otherField').clearValidators();
this.insertForm.get('otherField').addValidators(Validators.maxLength(this.maxlenght));
}
isValid() {
console.log(this.insertForm.valid);
}
在您的組件中yourcomponent.component.html
<div [formGroup]="insertForm">
<div>
<select name="select" formControlName="selectType" (change)="change()">
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
<div>
<input formControlName="otherField" [maxlength]="maxlenght" />
<small *ngIf="insertForm.get('otherField')?.errors" class="p-error">
maxlength exceeded
</small>
</div>
<div>
<button (click)="isValid()">is valid?</button>
</div>
</div>
一個完整的例子: https ://stackblitz.com/edit/angular-ivy-1ajwxq?file=src/app/app.component.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521175.html
標籤:有角度的验证
下一篇:Java匯入陳述句中的錯誤“無法決議匯入javax.validation.constraints.NotNull和NotEmpty”
