我正在写一个Angular应用程序,我有一个HTML响应,我想显示。

我怎么做呢?如果我简单地使用绑定语法{{myVal}},它将编码所有HTML字符(当然)。

我需要以某种方式将一个div的innerHTML绑定到变量值。


当前回答

在Angular 2中,你可以做3种类型的绑定:

[property]="expression" ->任何html属性都可以链接到 表达式。在这种情况下,如果表达式更改属性将更新, 但反过来就行不通了。 (event)="expression" ->当事件激活时执行表达式。 [(ngModel)]="property" ->将属性从js(或ts)绑定到html。在此属性上的任何更新都将随处可见。

表达式可以是值、属性或方法。例如:'4','controller。var, getValue ()

例子

其他回答

我们总是可以将html内容传递给innerHTML属性以呈现html动态内容,但动态html内容也可能被感染或恶意。因此,在将动态内容传递给innerHTML之前,我们应该始终确保内容是经过消毒的(使用DOMSanitizer),这样我们就可以逃脱所有恶意内容。

试试下面的管子:

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: string) {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }
}

Usage:
<div [innerHTML]="content | safeHtml"></div>

如果你的angular(或任何框架)应用程序中有模板,并且你通过HTTP请求/响应从后端返回HTML模板,那么你就是在前端和后端混合模板。

为什么不只是离开模板的东西要么在前端(我会建议),或在后端(相当不透明的imo)?

如果将模板放在前端,为什么不直接用JSON响应后端请求呢?您甚至不需要实现RESTful结构,但是将模板放在一边可以使代码更加透明。

当其他人不得不处理您的代码(甚至您自己在一段时间后重新输入自己的代码)时,这将会得到回报!

If you do it right, you will have small components with small templates, and best of all, if your code is imba, someone who doesn't know coding languages will be able to understand your templates and your logic! So additionally, keep your functions/methods as small you can. You will eventually find out that maintaining, refactoring, reviewing, and adding features will be much easier compared to large functions/methods/classes and mixing up templating and logic between the frontend and the backend - and keep as much of the logic in the backend if your frontend needs to be more flexible (e.g. writing an android frontend or switching to a different frontend framework).

哲学,伙计:)

附注:你不需要实现100%干净的代码,因为这是非常昂贵的——特别是如果你必须激励团队成员;) 但是:你应该在干净的代码和你已经拥有的代码之间找到一个很好的平衡(也许它已经很干净了)

如果可以的话,看看这本书,让它进入你的灵魂: https://de.wikipedia.org/wiki/Clean_Code

Angular 2+支持渲染HTML的[innerHTML]属性绑定。如果以其他方式使用插值,则它将被视为字符串。

转换成。html文件

<div [innerHTML]="theHtmlString"></div>

导入.ts文件

theHtmlString:String = "enter your html codes here";

为了得到一个完整的答案,如果你的HTML内容是在一个组件变量中,你也可以使用:

<div [innerHTML]=componentVariableThatHasTheHtml></div>

在Angular 2中,你可以做3种类型的绑定:

[property]="expression" ->任何html属性都可以链接到 表达式。在这种情况下,如果表达式更改属性将更新, 但反过来就行不通了。 (event)="expression" ->当事件激活时执行表达式。 [(ngModel)]="property" ->将属性从js(或ts)绑定到html。在此属性上的任何更新都将随处可见。

表达式可以是值、属性或方法。例如:'4','controller。var, getValue ()

例子