Why use ViewContainerRef over *ngif?

后端 未结 1 706
[愿得一人]
[愿得一人] 2021-01-31 23:07

I could just do


But every document on inserting

相关标签:
1条回答
  • 2021-01-31 23:57

    TLDR;

    If you don't know what component will be used in a component template when putting together this template use viewContainerRef. If you do know the component beforehand but it can sometimes be hidden, use ngIf.

    Explanation

    ViewContainerRef is used to specify the insertion point of the dynamic component. When using ngIf you need to specify the component in html in advance. So if you have a spot where you will insert one of three components you will need to do the following:

    <my-awesome-component1 *ngIf="ConditionToIncludeComponent1"></my-awesome-component1>
    <my-awesome-component2 *ngIf="ConditionToIncludeComponent2"></my-awesome-component2>
    <my-awesome-component3 *ngIf="ConditionToIncludeComponent3"></my-awesome-component3>
    

    Whereas with viewContainerRef you need only one spot (usually specified using `ng-container). Using ngComponentOutlet it can be done like this:

    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;
    

    Or component manually using createComponent method:

    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);
    

    Besides inconvenience and a bloated html template the bigger problem with the ngIf approach is performance impact since three ngIf directives will have to perform some logic on each change detection cycle.

    For more information read:

    • Exploring Angular DOM manipulation techniques using ViewContainerRef
    0 讨论(0)
提交回复
热议问题