【问题标题】:How do you use @Input with components created with a ComponentFactoryResolver?如何将 @Input 与使用 ComponentFactoryResolver 创建的组件一起使用?
【发布时间】:2017-01-09 20:11:39
【问题描述】:

是否有一种方法可用于在动态创建的 Angular 2 组件上定义 @Input 属性?

我正在使用ComponentFactoryResolver 在容器组件中创建组件。例如:

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentName);

let componentRef = entryPoint.createComponent(componentFactory);

“entryPoint”在组件 HTML 中是这样的:

<div #entryPoint></div>

并在我的容器组件中定义为:

@ViewChild('entryPoint', { read: ViewContainerRef } entryPoint: ViewContainerRef;

这很好用,但我找不到让 @Input 属性在新创建的组件上工作的方法。我知道您可以在组件类上显式设置公共属性,但这似乎不适用于 ng-reflect。在进行此更改之前,我有一个用“@Input()”装饰的“选定”属性,这导致 Angular 将以下内容添加到 DOM:

<my-component ng-reflected-selected="true"></my-component>

有了这个,我能够动态更新标记以切换 CSS 类:

<div class="header" [class.active-header]="selected === true"></div>

根据一些搜索,我找到了一种使“@Output”按预期工作的方法,但我还没有为@Input 找到任何东西。

如果其他上下文有帮助,请告诉我,我很乐意添加。

【问题讨论】:

    标签: angular


    【解决方案1】:

    不,Angular2 绑定仅适用于静态添加到组件模板的组件和指令。

    对于所有其他情况,请使用https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service 中所述的共享服务

    你也可以使用

    let componentRef = entryPoint.createComponent(componentFactory);
    componentRef.instance.someProp = 'someValue';
    componentRef.instance.someObservableOrEventEmitter.subscribe(data => this.prop = data);
    

    【讨论】:

    • 如何更改组件生成的 DOM 元素的 .style 属性?即this.cmpRef._hostElement.nativeElement.style...不使用私有变量
    • 您可以将@HostBinding('style.border') borderStyle:string; 添加到组件中,然后将其设置为componentRef.instance.borderStyle = 'solid 3px red'; 不确定这是否是您想要的。否则动态设置样式的选项并不多。
    • 我设法通过将 ComponetRef 转换为“any”来使其工作:let componentRef = this.dynamicComponentContainer.createComponent(factory);让 dynamicRef = componentRef as any; dynamicRef.instance.change.subscribe(x => console.log(x));不确定这是否是个好主意,因为它破坏了动态创建组件的类型安全
    • 我认为CompinentRef&lt;MyComponent&gt; 应该也可以使用
    • 当我这样做时,componentRef.instance.someProp = 'someValue';不会在子组件上触发 ngOnChanges。是否需要为这项拖车工作完成更多步骤?
    【解决方案2】:

    The Günter Zöchbauer's answer 是正确的。但如果你和我一样,在组件模板中渲染@Input 数据时遇到问题,你应该试试这个:

    1. ngAfterViewInit 中运行您的组件创建代码。
    2. 在最后一行添加componentRef.instance.ngOnInit()
    3. 在动态创建的组件的ngOnInit 内部运行ChangeDetectorRefdetectChanges 方法。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 2017-06-18
      • 2012-12-09
      • 2023-03-17
      相关资源
      最近更新 更多