简体   繁体   English

jquery 在 Angular 渲染结果后得到应用

[英]jquery getting applied after rendering result in Angular

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.我试图根据字符串的字符数截断字符串,然后如果字符数大于 21,则使用 append 省略号。

I have added a truncate class on the div of html using jquery .我使用 jquery 在 html 的 div 上添加了一个截断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.一切正常,但是当页面被刷新时,文本开始显示,然后这个截断 class 被应用到它上面。

Here is my html code:这是我的html代码:

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

Here is my jquery code:这是我的 jquery 代码:

    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" ,如果text1text2text1="My name is xyz" ,我得到的结果是这样的,

text2="Hello Mr.xyz"

End result: "My name is xyz, hello..."最终结果: "My name is xyz, hello..."

I want the jquery to be applied applied before the text gets render on page.我希望在文本在页面上呈现之前应用jquery

Is there any way so that I can delay the rendering?有什么办法可以延迟渲染吗?

You are using Angular so you can directly use ngClass like this您正在使用 Angular 所以您可以像这样直接使用 ngClass

<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.如果您仍然想使用您的代码并解决渲染问题,请删除 setTimeout并将您的代码放入ngAfterViewInit中,如下所示。 This will update the text after the html page gets loaded.这将在 html 页面加载后更新文本。

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM