I am trying to learn how to create a reactive form using angular 2 and nested components. After reviewing a few tutorials and different solutions on git I have found this by jonathanbruno, which seems to answer many of the question I had.
After pulling the solution I found that when run it the description
value is only added to the model once the user starts typing in the input field and the default value I added does not show(I have added the solution to stackblitz to show what I mean).
I have looked for an answer to this problem and found this plunk which does not exibit the same issues. There are some obvious differences between the solution in "Plunker" and the solution by jonathanbruno, but I can't understand why the jonathanbruno solution isn't part of the model on page load.
My understanding is that [(ngModel)]="parentModel.description"
enables the two way binding between the component and the HTML
ParentComponent.ts
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html'
})
export class ParentComponent implements OnInit {
parentModel:ParentModel = new ParentModel();
parentFormGroup:FormGroup;
constructor(
private _formBuilder:FormBuilder,
private _cd:ChangeDetectorRef) { }
ngOnInit() {
this.parentFormGroup = this._formBuilder.group({
description: ['this does not show', Validators.required]
});
console.log(this.parentFormGroup);
}
addChild() {
this.parentModel.children.push(new ChildModel());
this._cd.detectChanges();
}
}
ParentComponent.html
<form [formGroup]="parentFormGroup">
<label for="description">Description</label>
<input type="text" [(ngModel)]="parentModel.description" formControlName="description"><br>
<button (click)="addChild()">Add Child</button><br>
<app-child-list [childrenList] = "parentModel.children" [parentFormGroup]="parentFormGroup"></app-child-list>
{{parentFormGroup.valid}}
<pre>{{parentModel | json}}</pre>
</form>
It's working as it should :
If you check the output in the console of below code , you will get the idea ,
this.parentFormGroup = this._formBuilder.group({
description: ['this does not show', Validators.required]
})
console.log(this.parentFormGroup.value);
that value is being set at first , then its overridden by the ngModel value that is not defined coz of that it goes blank