jquery getting applied after rendering result in Angular

Viewed 72

I am trying to truncate string based on the number of characters of the string and then append ellipsis if number of chars greater than 21.

I have added a truncate class on the div of html using jquery. Everything works fine but when page is getting refreshed, for a second the text is getting display and after that this truncate class is getting applied on it.

Here is my html code:

<span class="truncate">
    <span *ngIf="result.text1">
        {{result.text1 + "," }}
    </span>
    <span *ngIf="result.text2">
        {{result.text2 + "," }}
    </span>
</span>

Here is my jquery code:

    setTimeout(() => {
    jQuery('.truncate').each(function (i) {
        if (jQuery(this).text().length > 21) {
            jQuery(this).text(
                jQuery(this)
                    .text()
                    .substr(0, 21) + '...'
            );
        }
    });

The result I am getting is something like this if text1 and text2 are text1="My name is xyz",

text2="Hello Mr.xyz"

End result : "My name is xyz, hello ..."

I want the jquery to be applied applied before the text gets render on page.

Is there any way so that I can delay the rendering?

1 Answers

You are using Angular so you can directly use ngClass like this

<span class="truncate">
    <div *ngIf="result.text1" [ngClass]="{'text-ellipsis':result.text1.length > 25}">
        {{result.text1 + "," }} {{result.text1.length > 25}}
    </div>
<div *ngIf="result.text2" [ngClass]="{'text-ellipsis':result.text1.length > 25}>
        {{result.text2 + "," }}
    </div>
</span>

.text-ellipsis {
  white-space: nowrap;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
}

And If you still want to use your code and just solve the rendering issue, then remove the setTimeout and place your code inside ngAfterViewInit like below. This will update the text after the html page gets loaded.

ngAfterViewInit() {
$(".truncate").each(function(i) {
  if ($(this).text().length > 21) {
    $(this).text(
      $(this)
        .text()
        .substr(0, 21) + "..."
    );
  }
});

}

Related