angular 2 model driven nested form components

前端 未结 3 2078
走了就别回头了
走了就别回头了 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 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;
    
    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); 
        });
      }
    }
    

提交回复
热议问题