18910140161

带有HTML-Stack溢出的JavaScript字符串

顺晟科技

2022-10-19 13:53:16

89

我有一个类似以下内容的组件:

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  expandText: boolean = false;

  constructor() {}

  ngOnInit() {}

  stringShortener(text: string) {
    let str = text;

    if (this.expandText === false) {
      if (str.length > 80) {
        str =
          str.substring(0, 80 - 3) +
          '...' +
          ' ' +
          "<span style='color: red'>see more</span>";
      }
    } else {
      str = str + '...' + ' ' + "<span style='color: yellow'>see more</span>";
    }

    return str;
  }
}

在HTML端,它类似于:

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  expandText: boolean = false;

  constructor() {}

  ngOnInit() {}

  stringShortener(text: string) {
    let str = text;

    if (this.expandText === false) {
      if (str.length > 80) {
        str =
          str.substring(0, 80 - 3) +
          '...' +
          ' ' +
          "<span style='color: red'>see more</span>";
      }
    } else {
      str = str + '...' + ' ' + "<span style='color: yellow'>see more</span>";
    }

    return str;
  }
}

问题是,没有呈现的HTML。我试过了,这在某种程度上导致了一个跨度。但是如果跨度类似于:,或者即使我使用,嗯,样式也不会被应用。所以我只得到一个包含文本的span。

那么如何使用正确的呈现来完成此操作?

编辑: 我创建了一个Stackblitz来显示问题: https://stackblitz.com/edit/angulg-ivy-xdi3z5?file=src/app/app.component.html


顺晟科技:

似乎忘记了花括号:)

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  expandText: boolean = false;

  constructor() {}

  ngOnInit() {}

  stringShortener(text: string) {
    let str = text;

    if (this.expandText === false) {
      if (str.length > 80) {
        str =
          str.substring(0, 80 - 3) +
          '...' +
          ' ' +
          "<span style='color: red'>see more</span>";
      }
    } else {
      str = str + '...' + ' ' + "<span style='color: yellow'>see more</span>";
    }

    return str;
  }
}

问题是您将span标记作为文本传递块,因此Angular只是将其打印为普通文本。

您可以使用*NGIF指令实现所需的功能,该指令将显示所需的span块,方法是添加一个函数,该函数将告诉您文本是否太长。

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航