【问题标题】:Passing Components in Angular2在 Angular2 中传递组件
【发布时间】:2017-01-15 20:24:28
【问题描述】:

假设我想要非常抽象和模块化,并且我想将组件作为输入传递给我的子组件。

这可能吗?

我知道我可以传递输入并在内部创建组件,但有时我想传递不同的/组件,否则我将不得不为每个组件自定义代码并且我无法对操作进行抽象。

例如,假设我将组件 P 作为父组件,将 C 作为子组件,我对 C 这样的设计有特定的目的,并且我希望 C 作为可重用组件,以便在我想实现这个特定设计时使用里面有元素。

现在,如果我想让 C(两个独立的元素)环绕两个不同的组件,我们称它们为 A 和 B。我希望 P 在创建它们后将它们传递给 C 以保持设计抽象,同时能够只需将组件用作 C 中的变量。

【问题讨论】:

    标签: angular angular2-template angular2-directives


    【解决方案1】:

    是的,这是可能的。实际上,模块化组件的组合在 Angular2 中是如何工作的。

    例如,如果您有一个模态组件,并且您想在整个应用程序中使用它,但该组件只是一个包装器,需要向其添加动态组件。

    这是一个使用 ComponentFactoryResolver 的示例:

    @Component({
      selector: 'my-dynamic-component',
      template: 'this is a dynamic injected component !'
    })
    export class MyDynamicComponent {}
    
    
    @Component({ 
      selector: 'wrapper',
      template: `
      <div>
        <p>Wrapper Component</p>
        <template #dynamicComponent></template> 
      </div>
      `
    })
    export class WrapperComponent {
      @Input() contentComponent: any;
      @ViewChild('dynamicComponent', { read: ViewContainerRef })
    
      dynamicComponent: any;
    
      constructor(private componentResolver: ComponentFactoryResolver) {}
    
      ngAfterViewInit():void {
        const factory = this.componentResolver.resolveComponentFactory(this.contentComponent);
    
        this.dynamicComponent.createComponent(factory);
      }
    }
    
    
    @Component({
      selector: 'my-app',
      template: ` 
      <wrapper [contentComponent]="MyDynamicComponent"></wrapper>`
    })
    export class AppComponent {
        MyDynamicComponent: any = MyDynamicComponent;
    }
    

    灵感来自deprecated ComponentResolver answer
    可以找到另一种方法answer HERE

    Example PLUNKER

    【讨论】:

    • 在 rc5-6 中使用 ComponentFactoryResolve 解析器获取工厂
    • 感谢您的解释!
    猜你喜欢
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2018-07-15
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    相关资源
    最近更新 更多