角反应形式:将子组件值传递给父组件

Sid*_*u h 0 angular angular-reactive-forms

我在角度实现反应形式。我无法将价值从孩子传递给父母。

父表格示例:

<div class="fields-wrap" [formGroup]="parent">
<div class="input-wrap">
  <child-component></child-component>
</div>
<input type"button">Submit</div>
</div>
Run Code Online (Sandbox Code Playgroud)

儿童伴侣表格:

<div class="fields-wrap" [formGroup]="child">
<input type="text" formControlName="firstname" />
<input type="text" formControlName="lastname" />
<input type="text" formControlName="email" />
</div>
Run Code Online (Sandbox Code Playgroud)

当我单击从父组件提交时如何获得这些子值。谁能帮我?

pen*_*han 5

Instead of passing in Form as an @Input() you can use viewProviders which I find it a lot more cleaner to read.

To do this is very simple, in your child component typescript file you just need to add one property to your @Component

viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective }]
Run Code Online (Sandbox Code Playgroud)

So all together it would output like this:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
  viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective }]
})
Run Code Online (Sandbox Code Playgroud)

Example on stackblitz: https://stackblitz.com/edit/angular-ruxfee