【问题标题】:How use angular 5 components in raw html如何在原始 html 中使用 Angular 5 组件
【发布时间】:2018-06-24 19:15:26
【问题描述】:

我有一个带有 onClick 函数的组件,它返回带有角度组件的 HTML 代码,我想在模板上显示它。我该怎么做?

因为在当前状态下,我得到的只是“测试代码”,没有演示组件。

export class AppComponent {
  title = 'app';

  content;

  onClick(){
    console.log("Clicked!")
    this.content = "Test code <democomponent></democomponent>";
  }
}

 <div>
  <button (click)="onClick()">Click</button>
<div>
  <div [innerHtml]="content"></div>
</div>
</div>

【问题讨论】:

  • 简而言之:你不能。它需要编译 HTML,Angular 中 AOT 编译的全部目的是避免发布编译器。找到另一种方法来解决您要解决的实际问题。
  • 看看this

标签: angular angular5


【解决方案1】:

尽管它在 Angular 6 中运行,但这可能不是“最干净”的方法。

首先我创建了一个名为 dummy.ts 的组件,[你可以给它起任何你想要的名字...] 使用以下 ng 命令

ng generate component dummy

dummy.ts 组件内容中添加任何内容之前,我首先需要定义一个管道文件。为方便起见,我使用以下 ng 命令在同一 dummy.ts 组件文件夹中生成了管道:

ng generate pipe SafeHtml

然后我添加了以下代码:

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

@Pipe({
 name: 'safeHtml'
})

export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitized: DomSanitizer) {}

  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
}}

终于回到dummy.ts我添加了这个非常简单的基本代码。

import { Component, OnInit } from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { SafeHtmlPipe } from './safe-html.pipe';

@Component({
  selector: 'app-dummy',
  templateUrl: './dummy.component.html',
  styleUrls: ['./dummy.component.css']
})

export class DummyComponent implements OnInit {
   name:string;
   safeHtmlContent : string;
   dummyContent : string;

   onClick(){
     this.safeHtmlContent  = this.dummyContent;
   }

  constructor() {
    this.dummyContent  = '<h4>Some dummy title</h4><p>Some blah blah blah blah blah... dummy content</p>';
  }}

dummy.html 中我只是添加了以下内容:

<div>
 <button (click)="onClick()">Click</button>
</div>

<div [innerHtml]="safeHtmlContent"></div>

因此,当单击按钮时,它会显示预期的原始 HTML
希望这会有所帮助;)

【讨论】:

  • 好的,但是如果我需要在 dummyContent html 中使用 Angular 组件,例如 dummyContent = "Test code ";
猜你喜欢
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
  • 2018-08-12
  • 2018-08-14
  • 2019-01-03
  • 2019-11-17
相关资源
最近更新 更多