Angular 2+材料垫-芯片列表formArray验证

Asg*_*shi 4 angular2-forms angular-material2 angular angular-reactive-forms

如何验证mat-chip已将添加到中mat-chip-list。我正在使用ReactiveForms。我已经尝试过required验证器。

该值可以是名称列表,因此在提交表单之前,我需要确保名称列表中至少有1个名称。如果列表为空,mat-error则应显示错误消息。使用required验证器会使表单无效,而不管在列表中添加名称如何。

编辑:反应形式

我试图做一个自定义验证器,现在使用的是反应式表单,而不是模板驱动的表单,但是我无法使它正常工作。我编辑了以下代码以反映我的更改,并创建了此https://stackblitz.com/edit/angular-4d5vfj

的HTML

<form [formGroup]="myForm">
  <mat-form-field class="example-chip-list">
    <mat-chip-list #chipList formArrayName="names">
      <mat-chip *ngFor="let name of myForm.get('names').controls; let i=index;"
        [formGroupName]="i"
        [selectable]="selectable"
        [removable]="removable"
        (removed)="remove(myForm, i)">
        <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
      </mat-chip>

       <input placeholder="Names"
          [matChipInputFor]="chipList"
          [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
          [matChipInputAddOnBlur]="addOnBlur"
          (matChipInputTokenEnd)="add($event, asset)">
    </mat-chip-list>
    <mat-error>Atleast 1 name need to be added</mat-error>
  </mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)

TS

import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, FormArray} from '@angular/forms';
import {MatChipInputEvent} from '@angular/material';

@Component({
  selector: 'chip-list-validation-example',
  templateUrl: 'chip-list-validation-example.html',
  styleUrls: ['chip-list-validation-example.css'],
})
export class ChipListValidationExample {
  public myForm: FormGroup;

  // name chips
  visible = true;
  selectable = true;
  removable = true;
  addOnBlur = true;
  readonly separatorKeysCodes: number[] = [ENTER, COMMA];

  // data
  data = {
    names: ['name1', 'name2']
  }

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
    });
  }

  initName(name: string): FormControl {
    return this.fb.control(name);
  }

  validateArrayNotEmpty(c: FormControl) {
    if (c.value && c.value.length === 0) {
      return { 
        validateArrayNotEmpty: { valid: false }
      };
    }
    return null;
  }

  add(event: MatChipInputEvent, form: FormGroup): void {
    const input = event.input;
    const value = event.value;

    // Add name
    if ((value || '').trim()) {
      const control = <FormArray>form.get('names');
      control.push(this.initName(value.trim()));
      console.log(control);
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

  remove(form, index) {
    console.log(form);
    form.get('names').removeAt(index);
  }
}
Run Code Online (Sandbox Code Playgroud)

fri*_*doo 6

问题是,chipListerrorState没有被设置为truechipListFormArray状态INVALID

我面临着同样的问题,不知道为什么不能开箱即用,或如何将chipList形式为a的隐式实现FormArray

作为一种变通方法,您可以聆听状态更改FormArray和设置chipListerrorState手动:

@ViewChild('chipList') chipList: MatChipList;

ngOnInit() {
  this.myForm.get('names').statusChanges.subscribe(
    status => this.chipList.errorState = status === 'INVALID'
  );
}
Run Code Online (Sandbox Code Playgroud)

https://stackblitz.com/edit/angular-4d5vfj-gywxjz

  • 感谢您发布此信息。我在这上面花了很多时间。我希望像这样的东西被记录在某处。 (2认同)

Dil*_*lip 5

为了能够对 a 进行验证,mat-chip-list我们必须将 和 绑定mat-input在一起mat-chip-listFormControl如下所示

工作 Stackblitz 链接在这里

<form [formGroup]='group'>
  <mat-form-field class="example-chip-list">
    <mat-chip-list #chipList
                   required
                   formControlName="newFruit">
      <mat-chip *ngFor="let fruit of fruits"
                (removed)="remove(fruit)">
        {{fruit.name}}
        <mat-icon matChipRemove>cancel</mat-icon>
      </mat-chip>
      <input placeholder="New fruit..."
            formControlName="newFruit"
            [matChipInputFor]="chipList"
            [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
            [matChipInputAddOnBlur]="addOnBlur"
            (matChipInputTokenEnd)="add($event)" required>
    </mat-chip-list>
      <!-- add mat-error  -->
    <mat-error *ngIf="group.controls.newFruit.hasError('required')">required!</mat-error>
  </mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)