angular 2 model driven nested form components

前端 未结 3 2075
走了就别回头了
走了就别回头了 2021-02-06 08:35

What I have:

I am building an ionic 2 app and have built a basic angular 2 component that contains

  • An input field

  • A lab

相关标签:
3条回答
  • 2021-02-06 08:48

    What I did in my case (nested dynamic form as well) is somehow similar to Marcin's response.

    I'm passing existing FormGroup as parentForm and my Component's view looks like this:

    <fieldset [formGroup]="parentForm">
        <label *ngIf="label" [attr.for]="key">{{label}}</label>
        <input [id]="key" [type]="type" [formControlName]="key" />
    </fieldset>
    

    It suits my needs. Hope it can help you as well.

    UPDATE: I've created a library for speeding up dynamic forms creation. You can take a look to figure out how I use the technique from this answer: https://www.npmjs.com/package/dorf

    0 讨论(0)
  • 2021-02-06 09:07

    Thanks for the answers guys. In the end we created two components, a custom-form component and a custom-input component.

    We nest as many custom-input components as we need inside the custom-form component and the custom-form component uses @ContentChildren to identify and register all the child custom-input components.

    This way we don't have to pass the form into every input, and we don't have a mess of nested form groups for every input.

    // Each CustomInputText component exposes a FormControl and 
    // a control definition which has additional info about the control
    @ContentChildren(CustomInputText, {descendants: true})
    public customInputComponents: QueryList<CustomInputText>;
    
    private initialised;
    
    public ngAfterContentChecked() {
      // Only initialise the form group once
      if (!this.initialised) {
        this.initialised = true;
        this.customInputComponents.forEach((input)=>{
            this.formGroup.addControl(input.controlDefinition.id, input.formControl); 
        });
      }
    }
    
    0 讨论(0)
  • 2021-02-06 09:07

    You can @Input your loginForm into nested component, as let's say parentForm. Then register nested formGroup to parentForm on child component init, and unregister it on child component destroy.

    0 讨论(0)
提交回复
热议问题