![](/img/trans.png)
[英]Custom attribute for select option and accessing it from AbstractControl in Angular 5?
[英]Get sibling AbstractControl from Angular reactive FormArray - Custom Validation
我在 Angular 中有一個使用 Reactive 表單的 Contact 表單。 該表單包含firstName
、 lastName
和一個address
數組。 每個地址表單組都包含一個復選框,如果選中該復選框,則需要對 State 文本框以及最小和最大字符長度進行強制驗證。
我編寫了一個自定義驗證器,即“ stateValidator
”,我試圖獲取同級元素“ isMandatory
”,但我無法獲得控制權。
我嘗試了以下方法
control.root.get('isMandatory');
- 它返回null
control.parent.get('isMandatory');
- 拋出異常我在 stackoverflow 中找到了一些鏈接,但沒有可用的答案,有些答案也沒有給出解決方案,例如上面的代碼: control.root.get('isMandatory');
我從其中一個視頻教程中得到了這個,但沒有任何效果。
StackBlitz 中提供了完整的工作源代碼: https ://stackblitz.com/edit/angular-custom-validators-in-dynamic-formarray
app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, AbstractControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
public userForm: FormGroup;
constructor(private _fb: FormBuilder) {
this.userForm = this._fb.group({
firstName: [],
lastName: [],
address: this._fb.array([this.addAddressGroup()])
});
}
private addAddressGroup(): FormGroup {
return this._fb.group({
street: [],
city: [],
state: ['', this.stateValidator],
isMandatory: [false, [Validators.required]]
});
}
get addressArray(): FormArray {
return <FormArray>this.userForm.get('address');
}
addAddress(): void {
this.addressArray.push(this.addAddressGroup());
}
removeAddress(index: number): void {
this.addressArray.removeAt(index);
}
stateValidator(control: AbstractControl): any {
if(typeof control === 'undefined' || control === null
|| typeof control.value === 'undefined' || control.value === null) {
return {
required: true
}
}
const stateName: string = control.value.trim();
const isPrimaryControl: AbstractControl = control.root.get('isMandatory');
console.log(isPrimaryControl)
if(typeof isPrimaryControl === 'undefined' || isPrimaryControl === null||
typeof isPrimaryControl.value === 'undefined' || isPrimaryControl.value === null) {
return {
invalidFlag: true
}
}
const isPrimary: boolean = isPrimaryControl.value;
if(isPrimary === true) {
if(stateName.length < 3) {
return {
minLength: true
};
} else if(stateName.length > 50) {
return {
maxLength: true
};
}
} else {
control.setValue('');
}
return null;
}
}
應用程序組件.html
<form class="example-form" [formGroup]="userForm">
<div>
<mat-card class="example-card">
<mat-card-header>
<mat-card-title>Users Creation</mat-card-title>
</mat-card-header>
<mat-card-content>
<div class="primary-container">
<mat-form-field>
<input matInput placeholder="First Name" value="" formControlName="firstName">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Last Name" value="" formControlName="lastName">
</mat-form-field>
</div>
<div formArrayName="address">
<div class="address-container" *ngFor="let group of addressArray.controls; let i = index;"
[formGroupName]="i">
<fieldset>
<legend>
<h3>Address: {{i + 1}}</h3>
</legend>
<mat-checkbox formControlName="isMandatory">Mandatory</mat-checkbox>
<div>
<mat-form-field>
<input matInput placeholder="Street" value="" formControlName="street">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="City" value="" formControlName="city">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="State" value="" formControlName="state">
</mat-form-field>
</div>
</fieldset>
</div>
</div>
<div class="form-row org-desc-parent-margin">
<button mat-raised-button (click)="addAddress()">Add more address</button>
</div>
</mat-card-content>
</mat-card>
</div>
</form>
<mat-card class="pre-code">
<mat-card-header>
<mat-card-title>Users Information</mat-card-title>
</mat-card-header>
<mat-card-content>
<pre>{{userForm.value | json}}</pre>
</mat-card-content>
</mat-card>
請幫助我如何在自定義驗證器方法中獲取同級抽象控件。
我嘗試了以下幾個答案中指定的代碼
isPrimaryControl = (<FormGroup>control.parent).get('isMandatory')
它拋出一個錯誤ERROR Error: too much recursion
。 請幫助我如何解決這個問題。
您可能需要將父級轉換為FormGroup
,請嘗試使用:
if(control.parent) {
(<FormGroup>control.parent).get('isMandatory')
}
您可以像這樣從表單控件中獲取isMandatory
的值,我已經將您的stateValidator
方法更改為基本上將control
類型轉換為具體的子類,然后從controls
數組中您可以獲得formControls
stateValidator(control: AbstractControl): any {
let mandatory:boolean=false;
if(control.parent){
console.log('control',<FormGroup>control.parent.controls.isMandatory.value);
mandatory=<FormGroup>control.parent.controls.isMandatory.value;
}
if((typeof control === 'undefined' || control === null
|| typeof control.value === 'undefined' || control.value === null)&& mandatory) {
debugger;
return {
required: true
}
}
const stateName: string = control.value.trim();
let isPrimaryControl: AbstractControl=null;
if(control.parent){
isPrimaryControl=<FormGroup>control.parent.controls.isMandatory;
console.log(isPrimaryControl)
}
if(typeof isPrimaryControl === 'undefined' || isPrimaryControl === null||typeof isPrimaryControl.value === 'undefined' || isPrimaryControl.value === null) {
return {
invalidFlag: true
}
}
const isPrimary: boolean = isPrimaryControl.value;
if(isPrimary === true) {
if(stateName.length < 3) {
return {
minLength: true
};
} else if(stateName.length > 50) {
return {
maxLength: true
};
}
} else {
control.setValue('');
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.