1

My problem is with Template Driven Forms. I have two components (parent and child) and I want to pass default values for controls inside child component. In child component I have reference to the parent's form by viewProviders.

 viewProviders: [{provide: ControlContainer, useExisting: NgForm}] 

Code: Stackblitz

I want to know if it is possible to set default values for child controls from the parent without using ControlValueAccessor or passing values through Input().

Parent Component:

TS:

... model = { name: "Test", phone: 1234567890, // phone control is inside child component (nested-form) } ... 

HTML:

<form #form="ngForm"> <div class="form-group"> <label for="name">Name</label> <input [(ngModel)]="model.name" class="form-control" id="name" name="name" required type="text"> </div> <app-nested-form></app-nested-form> </form> 

Child Component

TS:

import { Component, Host } from '@angular/core'; import { ControlContainer, NgForm } from '@angular/forms'; @Component({ selector: 'app-nested-form', templateUrl: './nested-form.component.html', viewProviders: [{ provide: ControlContainer, useExisting: NgForm }], }) export class NestedFormComponent { model: any = { phone: '', }; constructor(@Host() controlContainer: ControlContainer) { console.log((controlContainer as NgForm).form); // phone control exists in form but without value } } 
3
  • 1
    Any reason you wouldn't use reactive forms for this? Commented Apr 3, 2022 at 17:46
  • I would really love to do that, but the whole project is written using Template Driven Forms... Therefore I am looking for a good solution using TDF. Commented Apr 3, 2022 at 19:54
  • 1
    I'd argue that there isn't a good solution using TDF, you'll always be building workarounds. Angular provides a tool for this kind of situation (reactive forms), so if whoever's running the project insists on using TDFs, you'll always have a suboptimal result. Commented Apr 4, 2022 at 12:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.