Skip to content

Transcluded components hooks works incorrectly with upper *ngIf state #13921

Closed

Description

@artaommahe

I'm submitting a ... (check one with "x")

[ x ] bug report
[ ] feature request
[ ] support request

Current behavior
Transcluded via ng-content components OnInit and AfterViewInit hooks are triggered despite parent component ngIf state. OnDestroy hook does not triggered on removing from DOM.

Expected behavior
Hooks should be triggered only when component really are added/removed from DOM.

Minimal reproduction of the problem with instructions
Plnkr http://plnkr.co/edit/RkOXyEtvMNoSNLeAh8Jf?p=preview

MenuItemComponent OnInit and AfterViewInit hooks triggered despite MenuComponent ngIf false value and OnDestroy never fires despite component removing from DOM.

  • Angular version: 2.4.3

update
added one more plnkr - anything inside <menu> component will be initialized with all children despite it never will be added to dom due to closed menu. Comment bellow #13921 (comment)
http://plnkr.co/edit/2aaRtK3rppO9Qi8zWaWi?p=preview

Activity

  1. mhevery commented on Jan 13, 2017

    @mhevery
    Contributor

    Works as intended. view children are always created regardless if they are projected or not. This is by design.

  2. artaommahe commented on Jan 13, 2017

    @artaommahe
    ContributorAuthor

    @mhevery em.. but what with menu/tabs components if their items depends on some data that should be updated before menu is opened and has a lot of handlers in OnInit AfterViewInit OnDestroy hooks? Why this components should be init when they are not needed and should not do anything, that is controlled by upper ngIf.

  3. artaommahe commented on Jan 13, 2017

    @artaommahe
    ContributorAuthor

    Also as i understand AfterViewInit guarantees that component is added to DOM here that is wrong with this transclusion behavior.

  4. mhevery commented on Jan 13, 2017

    @mhevery
    Contributor

    Then enclosed the content of in *ngIf. This is how web-components work and we are just following the spec here.

  5. artaommahe commented on Jan 13, 2017

    @artaommahe
    ContributorAuthor

    @mhevery so for any component there is no guarantees that init/destroy hooks will be related to component DOM existing state and depends on outer context that cant be detected from this component?

  6. artaommahe commented on Jan 13, 2017

    @artaommahe
    ContributorAuthor

    I cant understand how this should be useful with menu-like elements that always uses transclusion and menu items should not be initialized until they are realy added (menu is open). It breaks all menu behavior logic.
    Also this means that there is no one hook for components that will reflect to component adding/removing from DOM state, am i right?

  7. mhevery commented on Jan 13, 2017

    @mhevery
    Contributor

    Your demo has:

    <menu>
      <menu-item></menu-item>
    </menu>
    

    Therefore menu-item instantiates in all circumstances. One can not have proper encapsulation if internal implementation details of menu will determine wether or not menu-item will be instantiated. We need to be able to reason about things without having global application knowledge.

    Sorry this behaves as intended.

  8. artaommahe commented on Jan 14, 2017

    @artaommahe
    ContributorAuthor

    @mhevery but what with hooks? Does this realy mean that they have nothing to do with component DOM state?
    It would follow that any code that depends on component template, children components/directives or component DOM instance should have a lot of checks to determinate if component in DOM or not.

    Also with tabs - if we have any heavy work in component that is hidden tab, this work will be done despite tab is active or not. It could be a lot of http/websocket requests, data formating or smth like this.

    Any common menu or tabs components works like this

    <menu>
      <menu-item></menu-item>
    </menu>
    
  9. artaommahe commented on Jan 14, 2017

    @artaommahe
    ContributorAuthor

    There is more - anything inside <menu-item></menu-item> will be instantiated too, despite it's needed or not.
    http://plnkr.co/edit/2aaRtK3rppO9Qi8zWaWi?p=preview

    MenuItemComponent ngOnInit
    MenuItemContentComponent ngOnInit
    MenuItemContentComponent ngAfterViewInit
    MenuItemComponent ngAfterViewInit
    

    and all of this with no elements in dom, no OnDestroy calls..

  10. artaommahe commented on Jan 14, 2017

    @artaommahe
    ContributorAuthor

    Looks like solution is to use <template> around menu items and TemplateRef/[ngTemplateOutlet] in menu component, thx to Günter
    http://stackoverflow.com/a/41655566/5803093

    There is a big lack in ng2 documentation on this theme :(

  11. amcdnl commented on Jul 24, 2017

    @amcdnl
    Contributor

    I want to add this is definitely not expected and if not known and handled can cause huge performance issues in instances like tabs.

  12. montella1507 commented on Aug 1, 2018

    @montella1507

    if are Initi hooks called, even the component is not in DOM, why is not called NgOnDestroy aswell? I cannot see the logic there. When shall we unsubscribe from observable then?

    How should author of a component prevent his component from this behavior? How are we able to detect when is our component used in "ngIfed" component as transcluded component?

    isnt it a bad design when your component acts diametrally differently because of environment?

  13. mlc-mlapis commented on Aug 1, 2018

    @mlc-mlapis
    Contributor

    @montella1507 ... because the instance still exists ... it is instantiated / destroyed in relation to the host so also the life-cycles of it are controlled by the host and not by the component instance in which <ng-content>...</ng-content> is placed.

  14. montella1507 commented on Aug 1, 2018

    @montella1507

    @mlc-mlapis well that makes sense actually...

    <ABC> //ng-content inside 
      <Y (click)="foo()">  // transcluded
     </Y>
    </ABC>
    

    The Y instance is in ABC instance (thats what you said). However.. if this is your argument, why is not component Y in case:

    //abc.component.html
    <div *ngIf="boolean">
      <Y> </Y>
    </div>
    

    created with component X when the condition is false? In point of view it is the same... ABC is owner of Y component... this is not consistent..

    My question is what are the benefits of this design? Because it is not so obvious it behaves and it should behave like this...

  15. mlc-mlapis commented on Aug 1, 2018

    @mlc-mlapis
    Contributor

    @montella1507 ... what is exactly component X?

    Generally ... if the template abc.component.html of the component ABC contains ...

    <div *ngIf="boolean">
      <Y> </Y>
    </div>
    

    then <div *ngIf="true"> would mean creating a new instance of component Y and inserting it to the DOM and with <div *ngIf="false"> it is reversed.

    But with transcluded content, like ...

    <ABC> //ng-content inside 
      <Y (click)="foo()">  // transcluded
     </Y>
    </ABC>
    

    the instance of component Y is created in the same moment when the instance of the component ABC and it is kept regardless of the conditional logic and *ngIf applied on <ng-content> inside the template of ABC. All of that (generated JS code) is defined by Angular compiler when HTML templates are compiled (AOT / JIT) and not during run-time.

  16. montella1507 commented on Aug 1, 2018

    @montella1507

    @mlc-mlapis it was typo .. at first, ABC component was X in my text i had some problems with "encoding" in this editor.. sorry for that.

    I understood all you have written... but still cannot overcome how to solve that problem when your component is used in ng-content...

    When you are creaing your components, you have connected *View and *Init lyfecykle hooks with existence in DOM, because it works like that in every other situation...

    And now.. it works different way => lifecykle hooks are done yet but your component doesn't exist in DOM at all..

    Of course the fix in most scenarios lends in adding *ngIf to your component too..

    <abc *ngIf="boolean">
    <Y *ngIf="boolean">

    but if you look at that, you thinks it is not correct way...

  17. mlc-mlapis commented on Aug 1, 2018

    @mlc-mlapis
    Contributor

    @montella1507 ...

    lifecykle hooks are done yet but your component doesn't exist in DOM at all.

    Exactly ... Angular has its inner abstraction model which is applied to the DOM when necessary ... and it is true that the model contains more information then the DOM itself. That's also the reason why it is absolutely a wrong way to touch the DOM in those parts that are under control of Angular.

    Of course the fix in most scenarios lends in adding *ngIf to your component too.

    Not necessarily. The most important is to understand the difference. Only in the cases of really massive transcluded content it can be suitable to count with memory consumption, timing and so on.

    Also with Ivy new renderer on the way we will see what will be added to this area ... especially with relation to @ContentChild and @ContentChildren and more dynamic behavior of <ng-content> itself.

  18. trotyl commented on Aug 1, 2018

    @trotyl
    Contributor

    lifecykle hooks are done yet but your component doesn't exist in DOM at all.

    An Angular application can be entirely bootstrapped in a detach element, having a living component with detach element node is still valid case.

  19. montella1507 commented on Aug 1, 2018

    @montella1507

    @mlc-mlapis i got you, however,.. we cannot strictly abstract from DOM... It is relative common scenario when you need to call external 3rd party library like:

    ngAfterViewInit() { someExternalMapLibrary.init(el.nativeelement) }
    to create Map element on native element... the place you wanna make it is AfterViewInit, right? .. however .. if your AfterViewInit is called and "you" aree not in DOM it will fail?

    How do you wish to make your code safe (when manipulating DOM directly) if AfterViewInit is triggered, but you dont have needed elements in DOM?

    I have encountered this problem with ng-content when:

    1. Captcha in ng-content
    2. Google map in mat-tab
    3. any graph librabry in mat-tab
  20. trotyl commented on Aug 1, 2018

    @trotyl
    Contributor

    @montella1507 As "Angular application can be entirely bootstrapped in a detach element", any component MUST NOT assume their host elements being mounted in document (if wanted to be robust). If your case require it being attached, then the component should guard that by itself.

  21. mlc-mlapis commented on Aug 1, 2018

    @mlc-mlapis
    Contributor

    @montella1507 ... yep, you are right in that. Some of those third party libs are not able to work on the nodes which are not in DOM. Then you have to add some your custom logic to control what to invoke and when ... in relation if the node is or isn't in DOM.

  22. montella1507 commented on Aug 1, 2018

    @montella1507

    "Angular application can be entirely bootstrapped in a detach element"

    thats good point. So basically what is AfterViewInit hook for?

    From definition:
    "A lifecycle hook that is called after Angular has fully initialized a component's view"

    what is component's view? From my POV it is DOM in BrowserModule, native ui in nativescript etc...

    If i cannot take "AfterViewInit" as hook that takes in place when my component is in "View" - DOM or Native component tree.. why it even exists? What should i use it for, if i cannot to be sure something is in DOM, or Native component tree in nativescript?

  23. trotyl commented on Aug 1, 2018

    @trotyl
    Contributor

    @montella1507 DOM is only a representation, a detached element is totally valid DOM (there's no such thing of "in DOM"), just not being a descendant of document node.

  24. mlc-mlapis commented on Aug 1, 2018

    @mlc-mlapis
    Contributor

    @montella1507 ... component view is one of the element of the Angular abstraction model. The other thing is how BrowserModule implements it for DOM, ... and there are other possibilities ... SSR, web workers, ... totally AI environments 😄 ... hundred variants.

  25. montella1507 commented on Aug 1, 2018

    @montella1507

    @trotyl @mlc-mlapis well... you helped me a lot, thank you. both of you.

  26. angular-automatic-lock-bot commented on Sep 13, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  27. locked and limited conversation to collaborators on Sep 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions