问题描述
我正在尝试创建一个指令,通过添加指向以 @
符号开头的子字符串的链接来修改元素的 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');
是 appendingsomething
到元素文本的开头而不是替换.
this.elementRef.nativeElement.innerHTML
always has an empty string.this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', 'something');
is appendingsomething
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?
我尝试了 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>
这篇关于Angular - 如何从指令访问和替换 innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!