markdown Angular - 显示HTML而不进行清理/过滤

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Angular - 显示HTML而不进行清理/过滤相关的知识,希望对你有一定的参考价值。

# Angular - Display HTML without sanitizing/filtering

[SOURCE](https://stackoverflow.com/a/46825383/1602807), [SOURCE](https://medium.com/@AAlakkad/angular-2-display-html-without-sanitizing-filtering-17499024b079)

**IMPORTANT:** keeping scripts like this is very dangerous so make sure the scripts are safe before using this technique.

Create a custom `Pipe`:

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

@Pipe({ name: 'safeHtml' })
export class SafeHtmlPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) { }

    transform(html) {
        return this.sanitizer.bypassSecurityTrustHtml(html);
    }
}
```

Create a custom `Directive`:

```typescript
import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({ selector: '[runScripts]' })
export class RunScriptsDirective implements OnInit {
    constructor(private elementRef: ElementRef) { }
    ngOnInit(): void {
        setTimeout(() => { // wait for DOM rendering
            this.reinsertScripts();
        });
    }
    reinsertScripts(): void {
        const scripts = <HTMLScriptElement[]>this.elementRef.nativeElement.getElementsByTagName('script');
        const scriptsInitialLength = scripts.length;
        for (let i = 0; i < scriptsInitialLength; i++) {
            const script = scripts[i];
            const scriptCopy = <HTMLScriptElement>document.createElement('script');
            scriptCopy.type = script.type ? script.type : 'text/javascript';
            if (script.innerHTML) {
                scriptCopy.innerHTML = script.innerHTML;
            } else if (script.src) {
                scriptCopy.src = script.src;
            }
            scriptCopy.async = false;
            script.parentNode.replaceChild(scriptCopy, script);
        }
    }
}
```

Register them in `app.module.ts`:

```typescript
@NgModule({
    declarations: [
        ...
        SafeHtmlPipe,
        RunScriptsDirective
    ],
```

Use like this:

```html
<div [innerHTML]="content | safeHtml" runScripts></div>
```

以上是关于markdown Angular - 显示HTML而不进行清理/过滤的主要内容,如果未能解决你的问题,请参考以下文章

html 来自http://www.tutorialspoint.com/angular_material/angular_material_quick_guide.htm

html 来自http://www.tutorialspoint.com/angular_material/angular_material_quick_guide.htm

html 来自http://www.tutorialspoint.com/angular_material/angular_material_quick_guide.htm

html 来自http://www.tutorialspoint.com/angular_material/angular_material_quick_guide.htm

html 来自http://www.tutorialspoint.com/angular_material/angular_material_quick_guide.htm

html 来自http://www.tutorialspoint.com/angular_material/angular_material_quick_guide.htm