Reuse components in angular2 model driven forms

时光总嘲笑我的痴心妄想 提交于 2019-11-30 13:17:16

This can be accomplish by passing in our top level FormGroup to the child component and having the child component add itself into the higher level FormGroup using formGroupName that way the upper level FormGroup needs to know essentially nothing about the lower levels:

main.component.ts

template: `<...>
    <common-a [parentForm]="myForm"></common-a>
    <...>

We will also get rid of the formA, formB declarations as they are no longer used.

component-a.component.ts [formGroup] is our parent group, formGroupName is how we will identify and attach the component's controls as a group to work in the larger whole (they will nest inside the parent group).

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

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

     constructor(private _fb: FormBuilder) {}

     ngOnInit() {
         this.componentAForm = this._fb.group({
             valueA1: ['', Validators.required],
             valueA2: ['', Validators.required]
         });

         this.parentForm.addControl("componentAForm", this.componentAForm);
     }
}

Here's a plunker (note that I made component B a little more dynamic here just to see if it could be done, but the implementation above for is equally applicable to B): http://plnkr.co/edit/fYP10D45pCqiCDPnZm0u?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!