4

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 to be defined outside of the Component, so I think that TemplateRef is the most appropriate for this.

I'm struggling to find a way to bind the externally defined Control to the internal Form, through the use of formControlName

Here is a start of the implementation:

// expandable.component.ts

[...]
@Component({
  selector: 'expandable',
  templateUrl: 'app/component/common/expandable/expandable.component.html',
  styleUrls: ['app/component/common/expandable/expandable.component.css']
})
export class ExpandableComponent {
  @ContentChild('childTemplate') childTemplate: TemplateRef<any>;

  @Input() children: Array<any>;
  public form: FormGroup;

  constructor(private _changeDetector: ChangeDetectorRef,
              private _formBuilder: FormBuilder) {
    this.children = [];
  }

  public ngOnInit(): void {
    this.form = this._formBuilder.group({
      children: this._formBuilder.array([])
    });

    const arrayControl = <FormArray>this.form.controls['children'];
    this.children.forEach(child => {
      const group = this.initChildForm();
      arrayControl.push(group);
    });
  }

  private initChildForm(): AbstractControl {
    return this._formBuilder.group({
      key: ['Initial Key', [Validators.required]],
      value: ['Initial Value', [Validators.required]]
    });
  }

  public addChild(): void {
    const control = <FormArray>this.form.controls['children'];
    control.push(this.initChildForm());
    this._changeDetector.detectChanges();
  }
}

-

<!-- expandable.component.html -->

<form [formGroup]="form">
  <div class="form-group">
    <div formArrayName="children">
      <div *ngFor="let child of form.controls.children.controls; let i=index">
        <div [formGroupName]="i">
          <template 
             [ngTemplateOutlet]="childTemplate" 
             [ngOutletContext]="{ $implicit: child }"></template>
        </div>
      </div>
    </div>
  </div>
  <a (click)="addChild()">Add Child</a>
</form>

Attempt to define the the template externally:

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

I'm naively trying to bind the formControlName to the implicitly passed context from the outter , but with no luck, as I'm getting "Cannot find control with name: 'value'". Ideally, I would like to be able to do the formControlName binding into the expandable.component.html instead, but I see no way of doing this either.

Any thoughts about this?

Bruno D'Auria
  • 333
  • 5
  • 13

1 Answers1

4

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

nikk wong
  • 8,059
  • 6
  • 51
  • 68