简体   繁体   English

Angular - 如何在不同级别重用组件?

[英]Angular - How to reuse a component in a different level?

Imagine we have this component structure:想象一下我们有这样的组件结构:

app1
-- app1.component.html
-- app1.component.ts

parent1
    parent2
        app2
        -- app2.component.html
        -- app2.component.ts

How could I reuse the app2 component in the app1 ?如何在app1重用app2组件? For example, reuse a table (both HTML and logic on typescript) instead of copy and paste code.例如,重用表格(打字稿上的 HTML 和逻辑)而不是复制和粘贴代码。

I have searched for solutions like ng-template , but failed.我已经搜索了ng-template类的解决方案,但失败了。 Also, call the tag didn't work as well.此外,调用标签也不起作用。

If the tag didn't work inside app1 I assume that you are importing app2 component inside another module.如果标签在 app1 中不起作用,我假设您正在另一个模块中导入 app2 组件。 If we want to use component over multiple modules you need to import app2 ONLY in shared module then import that module to modules where you want to have that component.如果我们想在多个模块上使用组件,您只需要在共享模块中导入 app2,然后将该模块导入到您想要拥有该组件的模块中。

Make sure to export that component inside shared module.确保在共享模块中导出该组件。

Need to use componentFactoryResolver https://angular.io/guide/dynamic-component-loader For example you want to use ThirdComponent inside FirstComponent需要使用 componentFactoryResolver https://angular.io/guide/dynamic-component-loader例如你想在 FirstComponent 中使用 ThirdComponent

//HTML
<section #firstComp></section>

//TS
import { AfterViewInit, Component, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ThirdComponent } from '../third/third.component';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.scss']
})
export class FirstComponent implements OnInit, AfterViewInit {
  @ViewChild('firstComp',{read: ViewContainerRef}) firstComp: ViewContainerRef;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  ngOnInit(): void {    

  }

ngAfterViewInit() {
  const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ThirdComponent);
  const componentRef = this.firstComp.createComponent<ThirdComponent>(componentFactory);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM