Skip to content Skip to sidebar Skip to footer

Angular2: Bind Form Context To NgTemplateOutlet

I'm trying to define a Component containing a dynamic Form (using ReactiveForms) where the user should be able to add / delete Controls. The Controls can take many forms, and has

Solution 1:

Yes, this is possible:

You need to implement the ControlValueAccessor interface which ngModel and formControlName inject, like so:

@Directive({
  selector: 'control',
  providers: [
    {provide: NG_VALUE_ACCESSOR, multi: true, useExisting: SwitchControlComponent}
  ]
})
export class SwitchControlComponent implements ControlValueAccessor {
  isOn: boolean;
  _onChange: (value: any) => void;

  writeValue(value: any) {
    this.isOn = !!value;
  }

  registerOnChange(fn: (value: any) => void) {
    this._onChange = fn;
  }

  registerOnTouched() {}

  toggle(isOn: boolean) {
    this.isOn = isOn;
    this._onChange(isOn);
  }
}

html:

  <expandable>
    <template #childTemplate>
      <div [formGroup]="form">
         <input control class="form-control" 
           formControlName="value" />
         </template>
      </div>
  </expandable>

Further reading:

With new forms api, can't add inputs from child components without adding additional form tags


Post a Comment for "Angular2: Bind Form Context To NgTemplateOutlet"