在Angular中,如何动态地将某些单词包装在另一个html元素中?

问题描述 投票:1回答:2

我有这个简单的Angular组件:

@Component({
  selector: 'my-component',
  template: '<p>{{someString}}<p>',
})
export class MyComponent  {
  @Input() someString: string;
}

someString可以是任何长度的任何字符串。例如,假设someString的值为:

"If you want my body and you think I'm sexy, come on, sugar, tell me so."

在那种情况下,Angular生成的HTML基本上等同于:

<p>If you want my body and you think I'm sexy, come on, sugar, tell me so.</p>

我将如何修改MyComponent,以便它检测到sexy中单词someString的每次出现,并将Angular将该单词包装在另一个HTML元素(例如<b>)中。因此,在此示例情况下,它将生成类似以下内容的代码:

<p>If you want my body and you think I'm <b>sexy</b>, come on, sugar, tell me so.</p>

如果我想将每次出现的单词sexy都包装在Angular Component中而不是原生HTML元素中怎么办?这是否需要一种不同的方法?

html angular components angular-components
2个回答
1
投票

您可以尝试这个:D

@Component({
  selector: 'app-test',
  template: `
    <p [innerHTML]="stringFormatted()"></p>
  `,
  styles: []
})
export class TestComponent {

  someString = "If you want my body and you think I'm sexy, come on, sugar, tell me so.";

  stringFormatted() {
    return this.someString.replace(/sexy/g, '<b>sexy</b>');
  }
}

0
投票

[您可以使用类似下面的内容-在渲染主要句子之后,您可以用span元素替换特殊单词并应用CSS类,例如对该span标签说.special

从'@ angular / core'导入{组件,输入,ElementRef,AfterViewInit};

@Component({
  selector: 'my-component',
  template: '<p>{{sentence}}</p>'
})
export class MyComponent implements AfterViewInit {
  @Input() sentence: string;
  @Input() specialWord: string;

  constructor(private el: ElementRef) {
  }

  ngAfterViewInit() {
    this.el.nativeElement.innerHTML = this.el.nativeElement.
      innerHTML.replace(new RegExp(`${this.specialWord}`, 'g'), 
          `<span class="special">${this.specialWord}</span>`);
  }
}

为了使您的代码通用,可以对特殊单词使用附加的@Input()

在应用程序的styles.scss中,您可以定义CSS类.special

.special {
  font-weight: bold;
}

[如果您想知道为什么不能使用类似的逻辑将sentence的内容替换为以下内容:

    this.sentence = this.sentence.replace(new RegExp(`${this.specialWord}`, 'g'),
         `<span class="special">${this.specialWord}</span>`);

然后,请注意Angular将转义HTML标记,它们将在输出中按原样显示。因此,您将在浏览器中看到类似这样的内容,而不是样式化的跨度。

Hello, it's a <span class="special">beautiful</span> day and I am in a very <span class="special">beautiful</span> city

这就是为什么,我不得不求助于innerHTML以便在Angular将句子呈现给DOM之后进行替换。

© www.soinside.com 2019 - 2024. All rights reserved.