【问题标题】:how to send mat-chip-list in form如何以表格形式发送 mat-chip-list
【发布时间】:2018-08-28 20:48:38
【问题描述】:

如何在表单中发送 mat-chip-list 。即使元素仍然存在,我的提交按钮也被禁用。那么如何发送我的标签数组。请帮助!

这是我的表格form

下面是我到目前为止所做的代码。

<mat-form-field class="example-chip-list">
          <mat-chip-list #chipList>
            <mat-chip
              *ngFor="let tag of Tags"
              [selectable]="selectable"
              [removable]="removable"
              (removed)="remove(tag)">
              {{tag}}
              <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
            </mat-chip>
            <input
              placeholder="tags"
              [formControl]="tagsSet"
              [matChipInputFor]="chipList"
              [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
              [matChipInputAddOnBlur]="addOnBlur"
              (matChipInputTokenEnd)="add($event)">
      </mat-chip-list>
        </mat-form-field>

     removable = true;
  addOnBlur = false;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  Tags: string[] = [];
this.testSuiteForm = new FormGroup({
     
     tagsSet: new FormControl(null, [Validators.required]), 
    });
add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;
    // Add our tag
    if ((value || '').trim()) {
      this.Tags.push(value.trim());
    }
// Reset the input value
    if (input) {
      input.value = '';
    }
    this.tagsSet.setValue(null);
  }
  remove(Tags: string): void {
    const index = this.Tags.indexOf(Tags);
    if (index >= 0) {
      this.Tags.splice(index, 1);
    }
  }

  get tagsSet() {
    return <FormArray>this.testSuiteForm.get('tagsSet');
  }

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

    当你在 ts 文件中调用 add() 函数时,你可以将 setValue 用于 formControl

    添加基于 JSON 的字符串

    this.testSuiteForm.controls['tagsSet'].setValue(JSON.stringify(this.Tags));
    

    添加逗号分隔字符串

    this.testSuiteForm.controls['tagsSet'].setValue(this.Tags.toString());
    

    【讨论】:

    • 我试过了,但是标签数组没有进入 testsuiteform ! if ((value || '').trim()) { this.Tags.push(value.trim()); this.testSuiteForm.controls['tagsSet'].setValue(JSON.stringify(this.Tags)); }
    • 如果你打印控制台,log(this.testSuiteForm.value) thiscoming null value for tagsSet?
    • 非常感谢它的工作..它不工作因为我评论了formcontrol部分所以..谢谢你:)
    • 酷。乐意效劳。请接受并为我投票。
    • 嗨,您知道不使用 Tags 数组我可以直接推入 tagsSet,因为在编辑表单时我遇到了问题
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 2018-12-29
    • 2022-11-16
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多