'How to pass data from parent to child in template driven form
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|