Angular set variable after View Init

919 Views Asked by At

Situation: Currently I have two tabs on my site, both containing a text. The text has a fixed height and the content-overflow is not shown (overflow: hidden).

Problem: I would like to add three dots (icon) if my text is overflowing. To detect if overflowing occurs I use the following expression, that works perfectly and adds an expandButton if overflowing occurs.

isOverflown: boolean;
hasExpandButton: boolean;

[...]

const overflown = this.isOverflown() ? this.hasExpandButton = true : this.hasExpandButton = false;

The problem is, that I don't know where I should check if my content is overflowing, because I use this statement in two differnet locations (here: tabs).

If I choose ngAfterViewInit, const overflown is getting set to true if my content is overflowing on the first tab. BUT not on the second tab (if the content is there also overflowing). The reason for that is, that the view only gets rendered on the first tab and not on the second tab. Therefore if I switch to the second tab the ngAfterViewInit will not trigger.

I also tried to use other lifecycle-hooks, but none of them worked for me.

I thought maybe about ngAfterContentInit and use a variable to detect if ngAfterContentInit is called for the first time, but this did not work for me either.

Thank you in advance.

SOLUTION I disabled lazy loading for this component and that solved the issue.

2

There are 2 best solutions below

4
On

Try solving this using CSS:

.txt-overflow {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

so you can get rid of extra component logic

0
On

You can check it after the view inits (ngAfterViewInit) AND when user switches tab - add (click)="checkOverflow()" to the tab tag in html.