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

前端之家收集整理的这篇文章主要介绍了angular – 为什么使用ViewContainerRef而不是* ngif?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以这样做

<my-awesome-component *ngIf="ConditionToIncludeComponent"></my-awesome-component>

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

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

解决方法

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>

而使用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;

或者使用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);

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

欲了解更多信息:

> Exploring Angular DOM manipulation techniques using ViewContainerRef

猜你在找的Angularjs相关文章