Angular 2+材料垫-芯片列表formArray验证 [英] Angular 2+ material mat-chip-list formArray validation

查看:143
本文介绍了Angular 2+材料垫-芯片列表formArray验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I validate that a mat-chip has been added to the mat-chip-list. I am using ReactiveForms. I have tried with the required validator.

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

The value can be a list of names, so I need to make sure that there is atleast 1 name in my list of names before I can submit the form. If the list is empty then mat-error should display the error message. Using the required validator makes the form invalid, regardless of adding names to the list.

反应形式

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

I have tried to make a custom validator, and I am now using Reactive Forms instead of Template driven forms, but I cannot get it to work. I have edited the below code to reflect my changes and I have created this 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);
  }
}

推荐答案

问题是,当chipList的FormArray状态为INVALID时,未将chipList的errorState设置为true.

The problem is that the chipList's errorState isn't set to true when the chipList's FormArray status is INVALID.

我正面临着同样的问题,不知道为什么这不能立即解决,或者如何使用chipList的形式为FormArray隐式实现.

I'm facing the same problem and don't know why this isn't working out of the box or how this can be achieved implicitly with the chipList's form being a FormArray.

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

As a workaround you can listen to status changes from the FormArray and set the chipList's errorState manually:

@ViewChild('chipList') chipList: MatChipList;

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

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

这篇关于Angular 2+材料垫-芯片列表formArray验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆