【问题标题】:How to pass Data to viewContainerRef Component in Angular?如何在 Angular 中将数据传递给 viewContainerRef 组件?
【发布时间】:2020-11-07 05:44:20
【问题描述】:

当从 viewContainerRef 呈现数据时,如何将数据传递给子组件?在我的例子中,EventRegistrationComponent 有一个带有水龙头的导航栏,我用下面的渲染函数更改了 ng-template 组件。我可以切换到的每个组件都需要相同的事件信息

EventRegistrationComponent <ng-template appEventRegistration></ng-template>

 @ViewChild(EventRegistrationDirective, { static: true }) registrationHost: EventRegistrationDirective;
 otherFunction(){
     this.render(EventRegistrationInfoComponent);
 }

 public render(component): void {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component as any);
    const viewContainerRef = this.registrationHost.viewContainerRef;
    viewContainerRef.clear();
    const comp = viewContainerRef.createComponent(componentFactory);
    comp['event'] = this.event;
 }

指令

@Directive({
  selector: '[appEventRegistration]',
})
export class EventRegistrationDirective {
   constructor(public viewContainerRef: ViewContainerRef) { }
}

子组件

export class EventRegistrationInfoComponent implements OnInit {
   @Input() event: Event;

    ngOnInit(): void {
       console.log('Info Event');
       console.log(this.event); //undefined

   }
}

【问题讨论】:

    标签: angular components


    【解决方案1】:

    按照本指南:https://medium.com/@davembush/dynamically-add-components-in-angular-7dc62b2a58d3

    组件<ng-template #dynamicInsert></ng-template>

       @ViewChild('dynamicInsert', { read: ViewContainerRef }) dynamicInsert: ViewContainerRef;
       otherFunction(){
          const dyynamicComponent = this.render(EventRegistrationHomeComponent) as EventRegistrationHomeComponent;
          dyynamicComponent.event = this.event;
      }
    
      render(component: any): any {
        const componentFactory = 
        this.componentFactoryResolver.resolveComponentFactory(component);
        this.dynamicInsert.clear();
        return this.dynamicInsert.createComponent(componentFactory).instance;
      }
    

    没有指令,ChildComponent 与问题相同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2020-09-06
      • 2017-07-14
      • 1970-01-01
      相关资源
      最近更新 更多