为什么使用ViewContainerRef而不是*ngif?

Pra*_*esh 4 dom dom-manipulation angular-components angular

我可以这样做

<my-awesome-component *ngIf="ConditionToIncludeComponent"></my-awesome-component>
Run Code Online (Sandbox Code Playgroud)

但是动态插入组件的每个文档都基于ViewContainerRef.我喜欢它的功能.但是什么使它在*ngif上如此特别?

只需指出两者的优点和缺点.请.谢谢!

Max*_*kyi 6

TLDR;

如果您在使用此模板时不知道组件模板中将使用哪个组件viewContainerRef.如果您事先知道该组件但有时可能会被隐藏,请使用ngIf.

说明

ViewContainerRef用于指定动态组件的插入点.使用时ngIf需要在指定组件html 提前.因此,如果您有一个位置,您将插入三个组件之一,您将需要执行以下操作:

<my-awesome-component1 *ngIf="ConditionToIncludeComponent1"></my-awesome-component1>
<my-awesome-component2 *ngIf="ConditionToIncludeComponent2"></my-awesome-component2>
<my-awesome-component3 *ngIf="ConditionToIncludeComponent3"></my-awesome-component3>
Run Code Online (Sandbox Code Playgroud)

viewContainerRef您只需要一个点(通常使用`ng-container指定).使用ngComponentOutlet可以这样做:

template: `<ng-container ngComponentOutlet="componentToInsert"></ng-container>`

class MyComponent {

   const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);

    if (ConditionToIncludeComponent1) {
        componentToInsert = myAwesomeComponent1;
    else if (ConditionToIncludeComponent2) {
        componentToInsert = myAwesomeComponent2;
    else if (ConditionToIncludeComponent3) {
        componentToInsert = myAwesomeComponent3;
Run Code Online (Sandbox Code Playgroud)

或者使用createComponent方法手动组件:

template: `<ng-container #spot></ng-container>`

class MyComponent {
   @ViewChild('spot', {read: ViewContainerRef}) vc;

   const myAwesomeComponent1 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent2 = cfr.resolveComponentFactory(MyAwesomeComponent1);
   const myAwesomeComponent3 = cfr.resolveComponentFactory(MyAwesomeComponent1);

    if (ConditionToIncludeComponent1) {
        vc.createComponent(myAwesomeComponent1);
    else if (ConditionToIncludeComponent2) {
        vc.createComponent(myAwesomeComponent2);
    else if (ConditionToIncludeComponent3) {
        vc.createComponent(myAwesomeComponent3);
Run Code Online (Sandbox Code Playgroud)

除了不便和臃肿的html模板之外,该ngIf方法的更大问题是性能影响,因为三个ngIf指令必须在每个变化检测周期上执行一些逻辑.

欲了解更多信息:

  • @Prabesh,不,`ngIf`如果评估为'false`,则不会创建组件.但是将创建`ngIf`指令的实例.Angular将在更改检测期间在'ngIf`的每个实例上花费一些时间.如果在组合组件模板时不知道将使用哪个组件.如果您确实知道该组件但有时可以隐藏它,请使用`ngIf`.我会考虑一下这篇文章的建议,谢谢 (2认同)