Angular4 ng-content gets built when ngIf is false

后端 未结 3 692
我寻月下人不归
我寻月下人不归 2020-12-10 02:11

I have a problem with the new ng-content transclusion.

Let\'s say I have a component my-component that, in its ngOnInit() func

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 02:42

    Based on the comment of @nsinreal I found an answer. I find it to be a bit abstruse, so I'm trying to post it here:

    The answer is to work with ng-template and *ngTemplateOutlet.

    In the my-wrapper component, set up the template like this (my-wrapper.component.html):

    Click for more

    Note, that the [hidden] there is not really necessary, it hides the "raw" template of the child until it decides it is done loading. Just make sure, not to put it in a *ngIf, otherwise the *ngTemplateOutlet will never get triggered, leading to nothing happening at all.

    To set the detailRef, put this in the component code (my-wrapper.component.ts):

    import { ContentChild, TemplateRef } from '@angular/core';
    
    @Component({ ... })
    export class MyWrapperComponent {
        @ContentChild(TemplateRef) detailRef;
    
        ...
    }
    

    Now, you can use the wrapper like this:

    
        
            
        
    
    

    I am not sure, why it needs such complicated "workarounds", when it used to be so easy to do this in AngularJS.

提交回复
热议问题