Angular-如何从指令访问和替换in​​nerHTML [英] Angular - How to access and replace innerHTML from a directive

查看:65
本文介绍了Angular-如何从指令访问和替换in​​nerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一条指令,以通过将链接添加到以@符号开头的那些子字符串的方式来修改元素的innerHTML.

I am trying to create a directive that modifies the element's innerHTML by adding links to those substrings which start with @ symbol.

这是我到目前为止尝试过的,

This is what I have tried so far,

linkify.directive.ts

  constructor(private elementRef: ElementRef, private renderer: Renderer2) { 
      let elementText = this.elementRef.nativeElement.innerHTML;
      // elementText = '@user mentioned you';
      console.log(`Element Text: ${elementText}`);
      this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', this.stylize(elementText));
  }

我正在这样使用它

<p linkify> Hey @user check this out! </p>

在调试时,我观察到以下情况,

While debugging I have made the following observations,

  • this.elementRef.nativeElement.innerHTML始终有一个空字符串.
  • this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', 'something');附加 something到元素文本的开头,而不是替换.
  • this.elementRef.nativeElement.innerHTML always has an empty string.
  • this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', 'something'); is appending something to the beginning of the element's text instead of replacing.

问题1::如何访问元素的innerHTML?

问题2:如何通过指令设置元素的innerHTML?

Question 2: How to set the innerHTML of an element from a directive?

Stackblitz证明了这个问题

我尝试了> Renderer2 的文档,但这对我没有帮助.

I tried the documentation for Renderer2, but it's of no help for me.

推荐答案

如@ bryan60所建议的那样,理想的方法是创建管道而不是使用指令.

As @bryan60 suggested, The ideal way to do this is to create a pipe instead of a directive.

这是我最终创建的管道,

This is the pipe I ended up creating,

linkify.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'linkify'
})
export class LinkifyPipe implements PipeTransform {

  constructor(private _domSanitizer: DomSanitizer) {}

  transform(value: any, args?: any): any {
    return this._domSanitizer.bypassSecurityTrustHtml(this.stylize(value));
  }

  private stylize(text: string): string {
    let stylizedText: string = '';
    if (text && text.length > 0) {
      for (let t of text.split(" ")) {
        if (t.startsWith("@") && t.length>1)
          stylizedText += `<a href="#${t.substring(1)}">${t}</a> `;
        else
          stylizedText += t + " ";
      }
      return stylizedText;
    }
    else return text;
  }

}

用法:

<p [innerHTML]="sample | linkify"></p>

演示Stackblitz

这篇关于Angular-如何从指令访问和替换in​​nerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆