我正在写一个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

其他回答

我已经建立下面的库,这将有助于重新绑定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]属性在你的HTML,如下所示:

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

你的组件中是否有包含html标记或 需要在模板中显示的实体?传统的 插值不会工作,但是innerHTML属性绑定会 救援。

使用{{myVal}}不能正常工作!这不会拾取HTML标签,如<p>, <strong>等,只将其作为字符串传递…

假设你的组件中有这样的代码:

碰到弦!弦!弦!< /埃隆·马斯克>”

如果你使用{{myVal}},你会在视图中得到这个:

<strong>Stackoverflow</strong> is <em>helpful!</em>

但是使用[innerHTML]="myVal"使结果像预期的那样:

Stackoverflow很有用!

如果你想在Angular 2或Angular 4中使用它,同时还想保持内联CSS,那么你可以使用它

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

你可以为样式、链接和HTML应用多个管道,如下所示。HTML

<div [innerHTML]="announcementContent | safeUrl| safeHtml">
                    </div>

在.ts管道中为“URL”消毒器

import { Component, Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safeUrl' })
export class SafeUrlPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {}
    transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}

用于“HTML”消毒器的管道

import { Component, 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) {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }
}

这将在不影响任何样式和链接单击事件的情况下应用

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