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

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

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


当前回答

如果你的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

其他回答

如果[innerHTML]包含用户创建的内容,直接使用[innerHTML]而不使用Angular的DOM消毒器是不可取的。@GünterZöchbauer在他的回答中建议的safeHtml管道是一种净化内容的方法。下面的指令是另一个指令:

import { Directive, ElementRef, Input, OnChanges, Sanitizer, SecurityContext,
  SimpleChanges } from '@angular/core';

// Sets the element's innerHTML to a sanitized version of [safeHtml]
@Directive({ selector: '[safeHtml]' })
export class HtmlDirective implements OnChanges {
  @Input() safeHtml: string;

  constructor(private elementRef: ElementRef, private sanitizer: Sanitizer) {}

  ngOnChanges(changes: SimpleChanges): any {
    if ('safeHtml' in changes) {
      this.elementRef.nativeElement.innerHTML =
        this.sanitizer.sanitize(SecurityContext.HTML, this.safeHtml);
    }
  }
}

被使用

<div [safeHtml]="myVal"></div>

Angular 2.0.0和Angular 4.0.0 final

对于安全的内容

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

DOMSanitizer

潜在的不安全HTML需要使用angular的DOM杀毒器显式地标记为受信任,这样就不会剥离潜在的不安全内容

<div [innerHTML]="myVal | safeHtml"></div>

用一根管子

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

  transform(style) {
    return this.sanitizer.bypassSecurityTrustHtml(style);
    //return this.sanitizer.bypassSecurityTrustStyle(style);
    // return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
  }
}

在RC.1中,有些样式不能使用绑定语法添加

文档:https://angular.io/api/platform-browser/DomSanitizer

安全警告

相信用户添加的HTML可能会带来安全风险。之前提到的文档状态:

调用任意一个bypassSecurityTrust…api禁用Angular内置的对传入值的处理功能。仔细检查和审计进入此调用的所有值和代码路径。确保任何用户数据都为此安全上下文进行了适当的转义。更多详细信息请参见《安全指南》。

角标记

类似的

class FooComponent {
  bar = 'bar';
  foo = `<div>{{bar}}</div>
    <my-comp></my-comp>
    <input [(ngModel)]="bar">`;

with

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

不会导致Angular在foo中处理任何特定于Angular的东西。 Angular在构建时用生成的代码替换Angular特定的标记。在运行时添加的标记不会被Angular处理。

要添加包含特定于angular的标记(属性或值绑定、组件、指令、管道等)的HTML,需要添加动态模块并在运行时编译组件。 如何在Angular 2.0中使用/创建动态模板来编译动态组件?

[innerHtml]在大多数情况下是一个很好的选择,但当你需要在html中硬编码样式时,它会失败。

我想分享其他方法:

你所需要做的就是在你的html文件中创建一个div,并给它一个id:

<div #dataContainer></div>

然后,在你的Angular 2组件中,创建对这个对象的引用(这里是TypeScript):

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
    templateUrl: "some html file"
})
export class MainPageComponent {

    @ViewChild('dataContainer') dataContainer: ElementRef;

    loadData(data) {
        this.dataContainer.nativeElement.innerHTML = data;
    }
}

然后简单地使用loadData函数将一些文本附加到html元素。

这只是一种使用原生javascript的方式,但在Angular环境中。我不推荐这样做,因为这会使代码更加混乱,但有时也没有其他选择。

另见Angular 2 - innerHTML样式

动态添加元素到DOM的方法,正如在Angular 2文档中解释的那样,是使用@Angular/core中的ViewContainerRef类。

你要做的是声明一个指令,它将实现ViewContainerRef,并充当DOM上的占位符。

指令

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appInject]'
})
export class InjectDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

然后,在你想要注入组件的模板中:

HTML

<div class="where_you_want_to_inject">    
  <ng-template appInject></ng-template>
</div>

然后,从注入的组件代码中,注入包含你想要的HTML的组件:

import { Component, OnInit, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { InjectDirective } from '../inject.directive';
import { InjectedComponent } from '../injected/injected.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  @ViewChild(InjectDirective) injectComp: InjectDirective;

  constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
  }

  public addComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.createComponent(componentFactory);
  }

  public removeComp() {
    const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const componentRef = viewContainerRef.remove();
  }

}

我在Angular 2上添加了一个完全可用的演示应用,动态地将组件添加到DOM演示中

如果你的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