首页 > 解决方案 > 如何以角度创建 HTML?

问题描述

我已经在 React 上工作了一年。现在,我正在写角度。如何在 ts.file 中创建一段 html 代码?

作为反应,我这样做:

const example = (item: string): React.ReactNode => {
  return <p> something.... {item} </p>
}

我想在 Angular8+ 中做同样的事情

我知道一些方法来做到这一点。例如:

const example2= (name: string): string => {
  return `
    <div>  
       <p>heyyy ${name}</p>
    </div>
  `;
};

还有其他方法吗?

标签: htmlangulartypescript

解决方案


在 Angular 中,有几种方法可以做到这一点。如果您需要在 typescript 中生成 HTML,然后将其插入到模板中,您可以将 theDomSanitizerinnerHTML属性组合使用到其他元素中(例如 a span)。

下面是我上面建议的一个例子:

hello-world.component.ts

@Component({
    selector: "hello-world",
    templateUrl: "./hello-world.component.html",
    styleUrls: ["./hello-world.component.scss"]
})
export class HelloWorld {
   innerHTML: string = `<p>Hello, world!</p>`;
}

sanitze.pipe.ts

@Pipe({
   name='sanitize'
})
export class SanitizePipe {
   constructor(private sanitizer: DomSanitizer) { }
   transform(value: string): SafeHtml {
      return this.sanitizer.bypassSecurityTrustHtml(value);
   }
}

hello-world.component.html

<div [innerHTML]="innerHTML | sanitize"</div>

推荐阅读