我正在写一个Angular应用程序,我有一个HTML响应,我想显示。
我怎么做呢?如果我简单地使用绑定语法{{myVal}},它将编码所有HTML字符(当然)。
我需要以某种方式将一个div的innerHTML绑定到变量值。
我正在写一个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
其他回答
为了得到一个完整的答案,如果你的HTML内容是在一个组件变量中,你也可以使用:
<div [innerHTML]=componentVariableThatHasTheHtml></div>
只是在目前为止所有精彩的回答中补充一点:如果你正在使用[innerHTML]来渲染Angular组件,并且对它不能像我一样工作感到沮丧,可以看看我写的ngx-dynamic-hooks库来解决这个问题。
有了它,您可以从动态字符串/html加载组件,而不会影响安全性。它实际上也像[innerHTML]一样使用Angular的DOMSanitizer,但保留了加载组件的能力(以一种安全的方式)。
在这部《斯塔克布利茨》中可以看到它的作用。
这里已经提供了简短的回答:使用<div [innerHTML]="yourHtml">绑定。
然而,这里提到的其他建议可能具有误导性。当你绑定到这样的属性时,Angular有一个内置的清除机制。因为Angular不是一个专门的消毒库,所以它对可疑内容过于热心,不愿冒任何风险。例如,它将所有SVG内容清除为空字符串。
您可能会听到一些建议,通过使用DomSanitizer将内容标记为安全的bypassSecurityTrustXXX方法来“消毒”您的内容。也有使用管道的建议,该管道通常被称为safeHtml。
所有这些都是误导,因为它实际上绕过了消毒,而不是消毒你的内容。这可能是一个安全问题,因为如果您对用户提供的内容或任何您不确定的内容这样做,您就会为恶意代码攻击敞开大门。
如果Angular通过内置的清理功能删除了你需要的某些东西,你可以做的不是禁用它,而是将实际的清理工作委托给擅长这项任务的专用库。例如——DOMPurify。
我已经为它做了一个包装器库,这样就可以很容易地在Angular中使用它: https://github.com/TinkoffCreditSystems/ng-dompurify
它还有一个管道来声明式地净化HTML:
<div [innerHtml]="value | dompurify"></div>
与这里建议的管道的不同之处在于,它实际上通过DOMPurify进行消毒,因此适用于SVG。
编辑:Angular不再在Ivy渲染器中对CSS进行消毒,所以下面的信息(出于历史考虑)是不相关的:
要记住的一件事是,DOMPurify很适合净化HTML/SVG,但不适用于CSS。所以你可以提供Angular的CSS消毒器来处理CSS:
import {NgModule, ɵ_sanitizeStyle} from '@angular/core';
import {SANITIZE_STYLE} from '@tinkoff/ng-dompurify';
@NgModule({
// ...
providers: [
{
provide: SANITIZE_STYLE,
useValue: ɵ_sanitizeStyle,
},
],
// ...
})
export class AppModule {}
它是内部的——因此有了ɵ前缀,但这也是Angular团队在他们自己的包中使用它的方式。该库也适用于Angular Universal和服务器端渲染环境。
您可以使用几种方法来实现该解决方案。正如已经批准的答案中所说,你可以使用:
<div [innerHTML]="myVal"></div>
根据你想要实现的目标,你也可以尝试其他东西,比如javascript DOM(不推荐,DOM操作很慢):
演讲
<div id="test"></test>
组件
var p = document.getElementsById("test");
p.outerHTML = myVal;
属性绑定
Javascript DOM外部HTML
动态添加元素到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演示中