javascript - Angular HTML 绑定(bind)不起作用

标签 javascript angular

我正在尝试迭代一个数组并创建一个工作正常的 DOM,但 pipe 无法工作。我关注了这个example但这在这里也行不通。

这是 json

[{
  "question":"What is this in QUestiom?",
  "ans":"<strong> this </strong> is only question"

},{
  "question":"What is the output of following code ?",
  "ans":"vgvfvfg"
},{
  "question":"What is the output of following code ?",
  "ans":"fcfcff"
}]

HTML

  <div *ngFor="let ques of questionseries;let i =index" class="test">
  <div>
    <span [innerHTML]="ques.question | safeHTML"> </span>
  </div>
  <div>{{ques.ans}}</div>
</div>

自定义管道

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

@Pipe({
  name: 'safeHTML',
  pure:false
})
export class SafeHTMLPipe implements PipeTransform {
 constructor(private sanitizer:DomSanitizer){}
  transform(value: any, args?: any): any {
   console.log(value , args);
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
 }

这是工作 DEMO .我的期望是 this 将位于 strong 内部,但它只是正确渲染。

最佳答案

该行还需要绑定(bind)到innerHTML:

  <div>{{ques.ans}}</div>

如下:

  <div [innerHTML]="ques.ans | safeHtml"></div>

关于javascript - Angular HTML 绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51856903/

相关文章:

javascript - 获取 eslint 快速修复,以便在 VSCode 中的 HTML 中使用 JavaScript

javascript - 如果该项目被 ng-repeat 中的另一个选择框选中,则从 ng-option 中删除/隐藏该项目

javascript - 在 sharepoint javascript 模型的每个循环中同步执行QueryAsync

javascript - 将平方根符号发送到文本区域

javascript - 更改对象阵列后, ionic 选择选项不会刷新

jquery - 在 Ionic2 中选择打开弹出窗口时如何检测事件?

node.js - NPM安装显示错误

javascript - 将私有(private)类的作用域放在单独的文件中

路由器导出外的 Angular 分量

css - Bootstrap Dropdowns 按钮不适用于 Angular 8 组件