1

假设我有一个如下组件:

<app-my-typical-form>
  <app-child-in-content></app-child-in-content>
</app-my-typical-form>

哪里my-typical-form.component.html是:

<form #f="ngForm">
  <ng-content></ng-content>
</form>
<hr>
<h3>Here is my form from the parent:</h3>
{{f|json}}

child-in-content.component.htmlchild-in-content.component.ts如下:

<h2>
  My Form from the projected content is:
</h2>
<br>
{{myForm|json}}
@Component({
  selector: 'app-child-in-content',
  templateUrl: './child-in-content.component.html',
})
export class ChildInContentComponent {
  constructor(@Optional() public myForm: NgForm) { }
}

正如您在StackBlitz中看到的那样,myForminapp-child-in-content为空。但是,我的理解是,既然child-in-content是(种)孩子,NgForm我可以通过 DI 拥有它。由于内容投影,这显然不起作用。

那么,有没有办法在app-child-in-content组件中获取 NgForm(编辑:之前ViewInit)?

4

1 回答 1

1

这是您的分叉StackBlitz 链接

首先,您需要使用 @ViewChild() 装饰器引用 NgForm。

您的 App.Component.ts 是...

@ViewChild(ChildInContentComponent, {static:true})
    private wizardComponent: ChildInContentComponent;
    @ViewChild(MyTypicalFormComponent, {static:true})
    private TypicalForm: MyTypicalFormComponent;

ngAfterViewInit(){
      this.wizardComponent.myForm = this.TypicalForm.wizardComponent      
}

您的典型Form.component.ts 添加此...

@ViewChild('f', {static:true}) wizardComponent;
于 2019-11-26T13:02:52.037 回答