如何将多个值推送到表单中?

How to push more than one value into the form?

我想将输入数组推送到表单中。目前我总是得到 console.log 只有最新输入的值。如何推送所有输入值?我只是想知道我是否需要额外的表单数组。因为我可以在我的控制台中输出整个列表。所以我可以访问这些导入的数据,以便上传到服务器。

page.html

<form [formGroup]="form" (ngSubmit)="addTag(form.value)">
    <ion-item>
      <ion-input formControlName="tag" clearInput="true" placeholder="Tags" [(ngModel)]="tagInput" name="tagValue"></ion-input>
      <ion-button item-right type="submit" icon-only>
      <ion-icon name="checkmark"></ion-icon>
    </ion-button>
    </ion-item>
  </form>
  <ion-chip *ngFor="let tag of tagList; let i = index">
      <ion-icon name="pricetag"></ion-icon>
    <ion-label>{{ tag }}</ion-label>
    <ion-icon name="close-circle" (click)="removeChip(i)"></ion-icon>
  </ion-chip>

page.ts

form: FormGroup;

public tagList: any[] = [];

constructor() { }

addTag(formValue) {
    if (this.tagInput !== '') {  //no empty input
    this.tagList.push(formValue.tagValue);
    this.tagInput = '';
    }
  }


  ngOnInit() {
    this.form = new FormGroup({
      tag: new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.required, Validators.maxLength(20), Validators.minLength(1)]
      })
    });
  }

  confirm() {
    console.log(this.form);
  }

所以,根据您的代码,您实际上有一个表单和一个从该表单添加的项目数组...不确定为什么您需要一个表单数组或类似的东西。您的固定代码可以是这样的:

  <form [formGroup]="form" (ngSubmit)="addTag()">
    <ion-item>
      <ion-input formControlName="tag" clearInput="true" placeholder="Tags" name="tagValue"></ion-input>
      <ion-button item-right type="submit" icon-only>
      <ion-icon name="checkmark"></ion-icon>
    </ion-button>
    </ion-item>
  </form>
  <ion-chip *ngFor="let tag of tagList; let i = index">
      <ion-icon name="pricetag"></ion-icon>
    <ion-label>{{ tag }}</ion-label>
    <ion-icon name="close-circle" (click)="removeChip(i)"></ion-icon>
  </ion-chip>

摆脱反应式表单和模板表单的混合,只调用添加标签,不传入值。

  form: FormGroup;

  public tagList: any[] = [];

  constructor() { }

  addTag() { // properly access and reset reactive form values
    const tagCtrl = this.form.get('tag');
    if (tagCtrl.value) {
      this.tagList.push(tagCtrl.value);
      this.tagCtrl.reset(''); // reset() sets the value and resets validation
    }
  }

  ngOnInit() {
    this.form = new FormGroup({
      tag: new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.required, Validators.maxLength(20), Validators.minLength(1)]
      })
    });
  }

  confirm() {
    console.log(this.tagList); // just check your tagList instead of looking at the form
  }

你想多了。 FormArray 在某些情况下可能很有用,例如需要一些复杂的验证/错误消息功能,或者在添加标签后编辑标签的能力,但如果您只需要简单的删除,那么您就过度设计了。