繁体   English   中英

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

[英]How to push more than one value into the form?

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

页面.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>

页面.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 在某些情况下可能很有用,比如需要一些复杂的验证/错误消息功能,或者在添加标签后编辑标签的能力,但如果你只需要简单的删除,那么你就过度设计了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM