angular - 在 Angular2 中传递组件

标签 angular angular2-template angular2-directives

可以说我想要变得非常抽象和模块化,并且我想将组件作为输入传递给我的子组件。

这可能吗?

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

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

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

最佳答案

是的,这是可能的。实际上,这就是 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

关于angular - 在 Angular2 中传递组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39381855/

相关文章:

angular - 使用@viewchild 访问多个 viewchildren

angular - 为主题动态加载 css 文件

Angular 2 : Multiple layout files using interpolation

javascript - 如何使用 Angular 2 更改按钮单击时输入标签的禁用属性

javascript - 当我将属性作为字符串插入时,如何防止 Angular 进行数学运算

angular - 如何从 Service 获取 component.ts 中的可见数据(可观察模式)

json - 在 JSON.stringify () 处将循环结构转换为 JSON

javascript - Angular 9-更改 app.module.ts 中的 Angular Material 日期格式不会更改惰性模块中的日期选择器格式

typescript - Angular2 - 私有(private)变量是否可以在模板中访问?

Angular2 - 将值传递给使用 ComponentFactory 创建的动态组件