【问题标题】:Angular Material mat-chip validationAngular Material mat-chip 验证
【发布时间】:2018-10-02 06:00:41
【问题描述】:

如何验证用户是否在mat-chip-list 中选择了chip,并且仅当用户选择chip 表单时才有效。现在我在控件上设置了validators.required,但它不起作用。 这是我到目前为止所做的:


HTML

<mat-chip-list formControlName="packageName">
   <mat-chip *ngFor="let pkg of packages" selected="true" style="background-color:#8d6e63">
        {{pkg.value}}
   </mat-chip>
</mat-chip-list>

TS

ngOnInit() {
  this.form = new FormGroup({
    'packageName': new FormControl('', Validators.required),
})

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    这是我所做的:

    ... (matChipInputTokenEnd)="add($event, postForm.get('tags'))" />
    
    export interface Tag {
      name: string;
    }
    ...
    
    tags: Tag[] = [];
    ...
    
    add(event: MatChipInputEvent, form: AbstractControl | null): any {
      // add tag from keyboard
      const input = event.chipInput;
      const value = event.value;
      // Reset the input value
      if (input) {
        input.clear();
      }
      // Add tag
      if ((value || '').trim()) {
        this.tags.push({ name: tag.trim() });
      }
    
      // set value for validation  <--- key code here
      form?.setValue(this.tags);
    
      return this.tags;
    }
    

    这里的关键是在实际的表单控件中添加一个空值或空值。

    更新: - 我还找到了另一个使用 form groups 的版本。

    【讨论】:

      【解决方案2】:

      您可以使用form.status 获取表单状态VALID 或INVALID 或form.controls.packageName.errors 获取formControl 错误的数组,如果没有错误,则为null。

      Here is a running example using your code.

      【讨论】:

      • 感谢 ibenjelloun,这就像一个魅力。现在已经为此苦苦挣扎了将近几天。没想到这么容易。提供的工作示例帮助很大。感谢您为我整理这些内容。
      猜你喜欢
      • 2018-12-23
      • 2019-04-28
      • 2022-11-10
      • 2018-05-20
      • 2023-02-25
      • 1970-01-01
      • 2018-12-29
      • 2018-04-23
      相关资源
      最近更新 更多