Angular 5响应式表单-使用FormArray的patchValue方法不起作用。
创始人
2024-10-15 23:00:48
0

在Angular 5中,使用FormArray的patchValue方法时可能会遇到一些问题。以下是一个解决方法的示例代码:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent implements OnInit {
  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      items: new FormArray([])
    });

    // 添加初始控件
    this.addItem();
  }

  addItem() {
    const control = new FormControl('');
    (this.form.get('items') as FormArray).push(control);
  }

  removeItem(index: number) {
    (this.form.get('items') as FormArray).removeAt(index);
  }

  patchValues() {
    const values = ['Value 1', 'Value 2', 'Value 3'];

    // 清空控件
    while ((this.form.get('items') as FormArray).length) {
      (this.form.get('items') as FormArray).removeAt(0);
    }

    // 添加新的控件
    values.forEach(value => {
      const control = new FormControl(value);
      (this.form.get('items') as FormArray).push(control);
    });
  }
}

在上述代码中,我们创建了一个包含FormArray的FormGroup。在初始化时,我们添加了一个初始控件。addItem方法用于添加新的控件,removeItem方法用于删除控件。patchValues方法首先清空所有控件,然后使用新的值重新填充控件。

在模板中,你可以使用*ngFor循环来显示所有的控件,并且使用patchValues方法来重新填充控件。示例代码如下:

通过以上代码,你应该可以成功使用FormArray的patchValue方法来重新填充表单。

相关内容

热门资讯

透视了解!hhpoker辅助软... 透视了解!hhpoker辅助软件下载(透视)wepoker有插件吗,教程大纲(真是有挂)-哔哩哔哩1...
wejoker辅助器要钱玩吗!... wejoker辅助器要钱玩吗!线上德州的辅助器是什么(透视)软件-果然解迷有挂线上德州的辅助器是什么...
透视关于!wepoker透视有... 透视关于!wepoker透视有用吗(透视)wpk可以透视吗,教程窍门(有挂教学)-哔哩哔哩1、完成w...
aapoker真的假的!wep... aapoker真的假的!wepoker透视脚本下载(透视)挂-竟然详细存在有挂wepoker透视脚本...
透视关于!xpoker透视辅助... 透视关于!xpoker透视辅助(透视)约局吧德州透视,教程教程书(有挂规律)-哔哩哔哩约局吧德州透视...
hhpoker软件靠谱吗!we... hhpoker软件靠谱吗!wepoker私人局开挂视频(透视)教程-一直推荐是真的挂亲,关键说明,w...
透视关于!aapoker辅助工... 透视关于!aapoker辅助工具安全吗(透视)werplan辅助软件,教程绝活儿(确实有挂)-哔哩哔...
德普之星辅助工具如何设置!we... 德普之星辅助工具如何设置!wepoker轻量版书签(透视)工具-一直教你真的有挂德普之星辅助工具如何...
wepoker怎么拿到好牌!w... wepoker怎么拿到好牌!wepokerplus透视脚本免费(透视)插件-确实解谜有挂1、超多福利...
透视专业!wepoker好友局... 透视专业!wepoker好友局透视(透视)wepoker透视最简单三个步骤,教程项目(有挂技术)-哔...