Angular 2+材料mat-chip-list formArray验证

问题描述 投票:2回答:2

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

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

编辑:反应形式

我试图制作一个自定义验证器,我现在使用Reactive Forms而不是模板驱动的表单,但我无法让它工作。我编辑了以下代码以反映我的更改,我创建了这个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>

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);
  }
}
angular angular2-forms angular-material2 angular-reactive-forms
2个回答
5
投票

问题是当chipListerrorState状态是true时,chipListFormArray没有设置为INVALID

我面临着同样的问题,并且不知道为什么这不是开箱即用的,或者如何用chipList的形式隐含地实现FormArray

作为一种解决方法,您可以从FormArray收听状态更改并手动设置chipListerrorState

@ViewChild('chipList') chipList: MatChipList;

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

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


1
投票

不幸的是,不可能使用任何Angular的预定义验证器,因为它们不适用于数组。我设法在本文的帮助下完成:

https://www.dev6.com/Angular_Material_Chips_with_Reactive_Forms_and_Custom_Validation

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.