FormArray中的重复数组验证器(呈角形)

时间:2019-02-10 16:42:57

标签: angular angular7 reactive-forms

我要添加Alias()方法的addInputs onclick,基本上是在某些条件下添加新的输入文本字段。

为此,我正在尝试创建custom duplicate array validator directive(同步或异步formArray验证器)。这意味着Alias formArray应该与Alias formArray中的其他元素一起验证当前输入中的文本。如果没有重复,则添加新的输入,否则警告重复的文本;

alias = ['abc','abc'] <---如果输入的文本与其他字符匹配,则验证失败。

.ts

    export class AppComponent implements OnInit {
        profileForm: FormGroup;
        aliaseS: FormArray;
        myInputs: FormArray;

        constructor(
            private formbuilder: FormBuilder
        ) {
            this.profileForm = this.formbuilder.group({
                firstName: ['', Validators.required],
                lastName: [''],
                contact: this.formbuilder.group({
                    mobileNo: [''],
                    state: [''],
                    city: ['']
                }),
                aliases: this.formbuilder.array([
                    this.formbuilder.control('')//add duplicate array Validator
                ]),
                myInputs: this.formbuilder.array([
                    this.formbuilder.control('') //add duplicate array Validator
                ])
            })
        }

        ngOnInit() {
            this.aliaseS = this.profileForm.get('aliases') as FormArray;
            this.myInputs = this.profileForm.get('myInputs') as FormArray;
        }

        updateProfile() {
            this.profileForm.patchValue({
                firstName: 'affff',
                contact: {
                    mobileNo: '99898981'
                }
            })
            console.warn(this.profileForm.value);
        }
        onSubmit() {
            console.warn(this.profileForm.value);
        }

        getAliases() {
            return this.profileForm.get('aliases') as FormArray;
        }

        addInputs(key) {
//if duplicate array Validator  Validates as false then add row otherwise error

            if (key === 'aliases') {
           // if no duplicate text then
           this.aliaseS.push(this.formbuilder.control(''));
            } else if(key === 'myInputs '){
                 // if no duplicate text then
           this.myInputs.push(this.formbuilder.control(''));
            }
        }
        deleteAlias(pos) {
            this.aliaseS.removeAt(pos);
        }
    }

.html

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
    <label>First Name:
        <input type="text" formControlName="firstName" required />
    </label>
    <br/>
    <label>
        Last Name:
        <input type="text" formControlName="lastName">
    </label>
    <br/>
    <br/>
    <div class="col-12" formGroupName="contact">
        <h3> Contacts</h3>
        <br/>
        <label>
            Mobile No
            <input type="text" formControlName="mobileNo">
        </label>
        <br/>
        <label>
            State
            <input type="text" formControlName="state">
        </label>
        <br/>
        <label>
            City
            <input type="text" formControlName="city">
        </label>
    </div>
    <br/>
    <div class="col-12"  formArrayName="aliases">
        <h3> Aliases</h3>
        <br/>
        <button type="button" (click)="addInputs('aliases')">Add Alias</button>

        <br/>
        <div *ngFor="let address of aliaseS.controls; let i = index;">
            <label>
                Alias:
                <input type="text"  [formControlName]="i" >
                <span (click)="deleteAlias(i)"> Delete</span>
            </label>
        </div>
    </div>
    <div class="col-12"  formArrayName="myInputs">
        <h3> myInputs</h3>
        <br/>
        <button type="button" (click)="addInputs('myInputs')">Add myInputs</button>
        <div *ngFor="let address of myInputs.controls; let i = index;">
            <label>
                Alias:
                <input type="text"  [formControlName]="i" >
            </label>
        </div>
    </div>
    <br>
    <div class="col-12" >
            <br>
            <br>
        <button type="submit">Submit</button>
        <button type="button" (click)="updateProfile()">Update</button>
    </div>
</form>
<br />
<br />
<p>{{profileForm.status}}</p>

1 个答案:

答案 0 :(得分:0)

我几乎没有重构您的代码,现在它可以按预期工作。为了进行重复验证,我使用了unique validator of rxweb validation framework

这是在FormControl上应用唯一验证器的代码。

addControl(){
            return this.formbuilder.group({
             name:this.formbuilder.control('',RxwebValidators.unique())});
        }

就是这样。

在HTML方面,我使用了disable属性,并检查FormArray是否有效。如果有效,则将启用按钮,用户可以输入新元素。

这是HTML的代码:

 <button type="button" [disabled]="!profileForm.controls.aliases.valid" (click)="addInputs('aliases')">Add Alias</button>

我已经用stackblitz转换了您的代码并进行了更改,请参考 stackblitz example