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

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

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


当前回答

我已经建立下面的库,这将有助于重新绑定html格式的绑定。 请找到下面使用这个库的步骤。这个库基本上允许在AOT中注入JIT编译器代码

Install library using npm i angular-html-recompile Add below code in app.component.html file <pk-angular-html-recompile *ngIf="template !== ''" [stringTemplate]="template" [data]="dataObject"> </pk-angular-html-recompile> Use below code in app.component.ts file import { Component, OnInit, ViewChild } from '@angular/core'; import { AngularHtmlRecompileComponent, AngularHtmlRecompileService } from 'angular-html-recompile'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { @ViewChild(AngularHtmlRecompileComponent, { static: true }) comp !: AngularHtmlRecompileComponent; constructor( private angularHtmlRecompileService: AngularHtmlRecompileService) { } public dataObject: any; public template = `<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center"> <mat-card class="box"> <mat-card-header> <mat-card-title>Register</mat-card-title> </mat-card-header> <form class="example-form"> <mat-card-content> <mat-form-field class="example-full-width"> <input matInput placeholder="Username" [value]="Username" (keydown)="onControlEvent($event,'Username')"> </mat-form-field> <mat-form-field class="example-full-width"> <input matInput placeholder="Email" [value]="Email" (keydown)="onControlEvent($event,'Email')"> </mat-form-field> <mat-form-field *ngIf="isShow" class="example-full-width"> <input matInput placeholder="Password" [value]="Password" (keydown)="onControlEvent($event,'Password')"> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Choose a role...</mat-label> <mat-select (selectionChange)="onControlEvent($event, 'selectedValue')"> <mat-option [value]="roles" *ngFor="let roles of Roles">{{roles}} </mat-option> </mat-select> </mat-form-field> </mat-card-content> <button mat-stroked-button color="accent" class="btn-block" (click)="buttomClickEvent('submit')" >Register</button> </form> </mat-card> </div>`; ngOnInit(): void { this.angularHtmlRecompileService.sharedData.subscribe((respose: any) => { if (respose) { switch (respose.key) { case `Username`: // Call any method on change of name break; case `Password`: //Update password from main component this.comp[`cmpRef`].instance['Password'] = "Karthik"; break; case `submit`: //Get reference of all parameters on submit click //1. respose.data OR //use this.comp[`cmpRef`].instance break; default: break; } } }); this.prepareData(); } prepareData() { //Prepare data in following format only for easy binding //Template preparation and data preparation can be done once data received from service // AngularHtmlRecompileComponent will not be rendered until you pass data this.dataObject = [ { key: 'Username', value: 'Pranay' }, { key: 'Email', value: 'abc@test.com', }, { key: 'Password', value: 'test123', }, { key: 'Roles', value: ['Admin', 'Author', 'Reader'] }, { key: 'isShow', value: this.updateView() } ]; } updateView() { //Write down logic before rendering to UI to work ngIf directive return true; } } Add module into app.module.ts file import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AngularHtmlRecompileModule } from "angular-html-recompile"; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AngularHtmlRecompileModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } This library supports basic html, Angular material, flex layouts. To use this features install below dependencies npm i -s @angular/material @angular/flex-layout

其他回答

如果[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>

请参考其他最新的答案。

这适用于我:<div innerHTML = "{{myVal}}"></div> (Angular2, Alpha 33)

根据另一个SO:用angular2将HTML从服务器插入到DOM中(angular2中的通用DOM操作),"inner-html"相当于Angular 1中的"ng-bind-html"。X

你可以使用以下两种方法。

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

or

<div innerHTML="{{myVal}}"></div>

我们总是可以将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>

<div [innerHTML]=“HtmlPrint”></div><br>

innerHtml是HTML-Elements的一个属性,它允许你以编程的方式设置它的html-content。还有一个innerText属性,它将内容定义为纯文本。

属性周围的[attributeName]="value"方括号定义了一个Angular输入绑定。这意味着,属性的值(在您的例子中是innerHtml)绑定到给定的表达式,当表达式结果改变时,属性值也会改变。

所以基本上[innerHtml]允许你绑定和动态改变给定html元素的html内容。