0

Fellows!

I'm writing a component, for example a table, for my web application. The table component is sometimes hidden, which means that it's in the component tree but not displayed to the user. For example:

<custom-tab> <!-- shown -->
  <custom-table /> 
</custom-tab>
<custom-tab> <!-- NOT shown -->
  <custom-table />
</custom-tab>

The hidden (not shown) custom-table component loads it's data inside the ngOnInit-method, which is executed by angular for both tables (shown and not shown). If I add a specific ngIf to the table (which evaluates if the tab is shown), the ngOnInit method is not called. This solution is very cumbersome, as there can be very complex scenarios of a large hierarchies of components which are deciding if a component is shown or not. Looking in the DOM of the browser, I see that correct custom-table elements are not present in the DOM. Angular initialises these components anyway (and calls ngOnInit).

Question:

  1. How does angular communicate that a component in is basically in the DOM and can't be shown (disregarding CSS)?
  2. How can one meaningful prohibit components from loading data if they are not shown, and only load data if they are displayed to the user?

Thanks!

Augunrik
  • 1,866
  • 1
  • 21
  • 28

2 Answers2

0

Talking from Angular 1 perspective, it works with a Two Way Data Binding. concept. This essentially means that the same piece of data is available to both view and model.

So whether you use ng-if or ng-show/ng-hide, the data is present in the view from the model, and vice versa. It's just a play of CSS (whether removing from DOM in case of ng-if or hiding in case of ng-show/hide)

sisyphus
  • 452
  • 5
  • 13
0

Not sure what 1) is about exactly. Perhaps this answers your question.

If the expression passed to *ngIf="..." evaluates to false, *ngIf removes the element from the DOM, and also a component on that element will be destroyed. When the expression evaluates to true, the element is added and the component recreated.

Angular2 checkes the expression every time change detection is executed.

You can use [hidden]="..." to prevent a component being removed but instead only be hidden.

See also What is the equivalent of ngShow and ngHide in Angular2?

2) Components don't load data if they are not added to the DOM. For example if an *ngIf="evaluatesToFalse" is added to the element. Besides that Angular doesn't know if a component is shown or not.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567