Angular2中的FormArray中的patchValue

4

正如我之前在问题中所问的那样。

我想创建一个嵌套表单,其中父级对子节点的formControlNames不知情。

因此,假设我们有一个组件componentA.component.ts

@Component({
    selector: 'common-a',
    template: `
    <div [formGroup]="parentForm">
        <div class="form-group">
        <label>Common A[1]</label>
        <div >
            <input type="text" formControlName="valueA1">
            <small>Description 1</small>
        </div>
        <div class="form-group">
        <label>Common A[2]</label>
        <div >
            <input type="text" formControlName="valueA2">
            <small>Description 2</small>
        </div>
    </div>
    `
})


export class ComponentA implements OnInit{
    @Input() parentForm: FormGroup;


    constructor(private _fb: FormBuilder) {
    }

    ngOnInit() {

      this.parentForm.addControl("valueA1", new FormControl('', Validators.required));
      this.parentForm.addControl("valueA2", new FormControl('', Validators.required));
    }
}

还有主要组件。

@Component({
    selector: 'main',
    template: `
    <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
        <div>
          <div *ngFor="let c of myForm.controls.componentA.controls; let i=index" class="form-group">
            <common-a [parentForm]="c"></common-a>
          </div>
            <div>
                <button type="submit" [disabled]="myForm.invalid">Register!</button>
                <a class="button" (click)="add_component()">Add New</a>
                <a class="button" (click)="delete_component()">Delete</a>
            </div>
        </div>
         <pre>form value: <br>{{myForm.value | json}}</pre>
    </form>
    `
})
export class MainComponent implements OnInit{
    @Input('group') public myForm: FormGroup;

    add_component() {
      const control = <FormArray>this.myForm.controls['componentA'];
      control.push(this._fb.group({}));
    }

    delete_component() {
      const control = <FormArray>this.myForm.controls['componentA'];
      control.removeAt(this.myForm.length-1);
    }

    constructor(private _fb: FormBuilder) {
    }

    ngOnInit() {
        this.myForm = this._fb.group({
          componentA : this._fb.array([this._fb.group({})])
        });
    }

    onSubmit(formValue) {
      console.log(formValue);
    }
}

我的问题是如何使用patchValue从服务器端点获取数据并填充表单数组的值,根据需要创建新的FormGroups,始终与父级无关。

  1. 我能想到的一种方法是父组件生成新的子组件。

这种方法的问题除了架构不良之外,还有一个问题就是我需要在覆盖patchValue方法中推送这些新的组,因为在函数体内我知道有多少个组,但是子组件的OnInit不会在函数内调用,导致这些值为空。

var self = this;
this.formArray.patchValue = (value: {[key: string]: any}, {onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}) =>{
    for(var i = 0; i < Object.keys(value).length; i++ ) {
        self.add_new();
    }
    Object.keys(value).forEach(name => {
        if (self.formArray.controls[name]) {
            self.formArray.controls[name].patchValue(value[name], {onlySelf: true, emitEvent});
        }
    });
    self.formArray.updateValueAndValidity({onlySelf, emitEvent});
}
  1. 另一个选择是让这个程序员提供一个静态函数来暴露它内部的组成。

我认为这是糟糕的设计。

static generate() {
    return new FormGroup({
        valueA1: new FormControl('', Validators.required),
        valueA2: new FormControl('', Validators.required)
    }); 
}

您有没有这种问题的清洁解决方案?

此外,这里是一个基于我之前的问题的工作的Plunkr


如果您能用简单的话语描述清楚您想要实现什么。 - kind user
我想要修补一个 JSON 值: { "componentA": [ { "valueA1": "asd", "valueA2": "asd" }, { "valueA1": "asd", "valueA2": "asd" } ] } 并且 MainComponent 推入具有正确值的新 FormGroup - stefanos
你找到解决方案了吗?@stevengatsios - WarrenV
我为 FormGroupFormArray 制作了自定义包装器,其中我接受一个 @Component 作为输入,并将视图注入 ElementRef 中以覆盖 patchValue 函数。目前代码库很混乱,但如果您愿意,我可以尝试写一个简短的答案。 - stefanos
1个回答

0

动态控件的替代解决方案。

1:注入ChangeDetectorRef

constructor(private _changeDetectorRef: ChangeDetectorRef) { }

2:覆盖patchValue

    this.control = new FormArray([]);
    let patchValue = this.control.patchValue;
    this.control.patchValue = (value: any, options?: Object) => {
      for (let i = this.control.length; i < value.length; i++) {
        // Push new item
      }

      this._changeDetectorRef.detectChanges();
      patchValue.apply(this.control, [value, options]);
    };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接