Include a component as FormControl Angular2

旧城冷巷雨未停 提交于 2019-12-05 20:11:49

A single Form Control cannot be passed separately to the child component, it has to be passed within a formGroup. So add a group (here named timeGroup) to your form:

this.newForm = this.fb.group({
      name: ['', [Validators.required]],
      surname:['', [Validators.required]],
      timeGroup: this.fb.group({
        time: ''
      })
});

In your parent html pass the formGroup to your child:

<time-comp [timeGroup]="newForm.controls.timeGroup"></time-comp>

and child template:

<div [formGroup]="timeGroup">
  <input formControlName="time">
</div>

And do not forget to mark the formgroup received from parent with Input:

@Input() timeGroup: FormGroup;

Then you can access the time value (in your parent) with:

this.newForm.get('timeGroup').get('time').value;

Also notice that you do not need any events, like keyup, the changes will be catched by the parent without them.

Sample Plunker

As of Angular 8, it is possible to pass FormControl as a @Input to a child component without having to put it inside a formGroup and it would still work with two-way binding. An example.. https://angular-v2yaaw.stackblitz.io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!