【问题标题】:Load component dynamically in Angular [duplicate]在Angular中动态加载组件[重复]
【发布时间】:2020-04-17 09:28:23
【问题描述】:

我收到要在特定时间显示的所有组件,因此我正在对其进行迭代。 我已经尝试过,如下所示。我已经创建了允许使用的组件来自服务器的组件

      <ngb-tabset [activeId]="1">
        <ngb-tab id="{{i+1}}" title="{{dir.Name}}" *ngFor="let dir of DefaultDirectives;let i=index">
          <ng-template ngbTabContent>
            //Custom Component According to name of directive name in iteration
          </ng-template>
        </ngb-tab>
      </ngb-tabset>

例如,我有这个:

 DefaultDirectives:any[]=[
         {Name:'First Directive',Directive:'app-dir1'},
         {Name:'Third Directive',Directive:'app-dir3'},
       ]

我拥有所有这些组件

@Component({
  selector: 'app-dir1',
  templateUrl: './dir1.component.html', 
})
export class Dir1Component  {
//Some Code
}



@Component({
  selector: 'app-dir2',
  templateUrl: './dir2.component.html', 
})
export class Dir2Component  {
//Some Code
}



@Component({
  selector: 'app-dir3',
  templateUrl: './dir3.component.html', 
})
export class Dir3Component {
    //Some Code
}

【问题讨论】:

  • 您应该了解组件和指令之间的区别。 angular.io/api/core/Directive
  • 我该怎么做才能让它像这样调用组件我可以做 但我选择器是动态的@Reactgular
  • 这里有很多不同的方法来做你想做的事。从开关到动态组件不等。看起来您想要动态,但ngSwitch 是最简单的(为什么要复杂化?)。无论如何,请阅读:angular.io/guide/dynamic-component-loader
  • 因为有 20-30 种不同的模板我必须使用,通常 3-5 会在那里
  • 如果我使用 switch case 代码会增加

标签: javascript angular typescript angular-material


【解决方案1】:

根据https://angular.io/guide/dynamic-component-loader中的解释,我曾经写过一个DynamicHost指令助手(在Angular 6项目中)

@Directive({
    selector: '[smaDynamicHost]',
})
export class DynamicHostDirective implements OnInit {
    @Input('smaDynamicHost') component: Type<any>;

    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private viewContainerRef: ViewContainerRef,
        private cdr: ChangeDetectorRef,
    ) {}

    ngOnInit(): void {
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
            this.component,
        );
        this.viewContainerRef.clear();
        this.viewContainerRef.createComponent(componentFactory);
        this.cdr.detectChanges();
    }
}

使用该指令,您现在可以简单地传递要动态加载的组件的类型。用你的例子,它应该看起来像

<ng-template ngbTabContent [smaDynamicHost]="dir.Directive"></template>
 DefaultDirectives:any[]=[
    {Name: 'First Directive', Directive: Dir1Component},
    {Name: 'Third Directive', Directive: Dir3Component},
]

重要提示:您必须在 Angular 模块中将动态组件声明为 entryComponents

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2019-10-19
    • 2019-02-06
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2021-12-20
    • 2017-01-01
    • 2017-10-21
    • 2020-08-13
    相关资源
    最近更新 更多