Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2/4如何根据插入的数据自动更新阵列大小?_Angular_Angular2 Forms - Fatal编程技术网

Angular2/4如何根据插入的数据自动更新阵列大小?

Angular2/4如何根据插入的数据自动更新阵列大小?,angular,angular2-forms,Angular,Angular2 Forms,我的表单生成器有以下配置 this.fb.group({ id: [this.app.get('id'), []], tips: new FormArray([new FormControl('')]), }) 我想根据在setValue()或patchValue()期间插入的数据更新提示的大小。如果我有以下数据 { id: 123, tips: [ 'Drink water', 'Exercise' ] } 我希望阵列自动展开。Ang

我的表单生成器有以下配置

 this.fb.group({
            id: [this.app.get('id'), []],
            tips: new FormArray([new FormControl('')]),
 })
我想根据在setValue()或patchValue()期间插入的数据更新提示的大小。如果我有以下数据

{
 id: 123,
 tips: [ 'Drink water', 'Exercise' ]
}

我希望阵列自动展开。Angular有这样的功能吗?还是我必须检查数组的大小并在其中插入新控件?

让我们看看我是否正确理解您的意思

您需要收到的修补程序值。一个选项是使用
setControl()
,它取代了现有的
tips
FormArray

myObject={id:123,提示:[“喝水”,“锻炼”]}
然后做:

setValues(){
this.myForm.setValue({
id:this.obj.id,
})
//我喜欢在构造函数中注入'FormBuilder'并使用'fb'
this.myForm.setControl('tips',this.fb.array(this.obj.tips))
}

我遇到了一个类似的问题,我不想丢失我的
验证器
值更改
可见

最简单的解决方案是:

  • 将您的“提示”实例化封装到要重用的方法中
  • 使用
    removeAt()
    push()
    匹配传入值的长度
setFormValue(newValues:TipList):无效{
const tipArray:FormArray=this.myForm.get('tips');
//删除列表中的控件以匹配新值
while(tipArray.length>newValues.tips.length){
tipArray.removeAt(0);
}
//在列表中添加控件以匹配新值
while(tipArray.lengthconst-tip:FormControl=new-FormControl(“”);//注释:检查数组大小是什么意思?为什么需要检查大小?也许我很笨:)假设我插入数组的tips属性的大小为5,而数组初始化为只有一个表单控件;setValue()将抛出一个错误;因此,一种解决方案是根据我正在推送的数据的大小更新表单数组的大小;但是如果它能够自己完成这项工作,那就太好了。嘿,谢谢你,但这在我的情况下不起作用,因为我的数组中有验证器,所以我想我必须简单地在数组中循环并插入是的,那么我认为你需要这样做,至少我不知道其他的方法。。。
    setFormValue(newValues: TipList): void {
        const tipArray: FormArray = <FormArray>this.myForm.get('tips');

        // Remove controls in the list to match new value
        while (tipArray.length > newValues.tips.length) {
            tipArray.removeAt(0);
        }
        // Add controls in the list to match new value
        while (tipArray.length < newValues.tips.length) {
            tipArray.push(this.getNewTip());
        }

        // Finally set the incoming value
        this.myForm.setValue(newValues);
    }

    getNewTip(): FormControl {
        const tip: FormControl = new FormControl(''); // <- set validation here
        // Set other things like valueChange here
        return tip;
    }