【问题标题】:Not able to replace string by text box in TypeScript无法用 TypeScript 中的文本框替换字符串
【发布时间】:2018-10-02 03:40:21
【问题描述】:

我想在 Angular 2/4 中用文本框替换 __。在下面的链接中,我有示例。

https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts

【问题讨论】:

  • 请删除angularjs 标签。此标签保留给angular 1.x问题
  • 顺便说一句,我不明白你的问题。这甚至不是一个文本框!
  • @Cristian Traìna 没有任何文本框。我有一个字符串,其中包含 __。我想用一个文本框替换每个 __。

标签: javascript angular typescript


【解决方案1】:

组件模板中不能绑定未经处理的HTML,应该是marked as sanitized first:

constructor(private sanitizer: DomSanitizer) {}

replaceFillBlanks(question): SafeHtml {
  var $inputBox = '<input type="text" name="fillBox"/>';

  let q = this.sanitizer.bypassSecurityTrustHtml(question.replace(/__/g,$inputBox));
  return q;
}

【讨论】:

    【解决方案2】:

    Angular 会清理您的 HTML 以防止 XSS 攻击。你不能这么容易地注入html!您需要对其进行消毒。

    您可以使用bypassSecurityTrustHtml(value: string) 并阅读有关此over here 的更多信息。

    注意,假设你知道自己在做什么:

    这些情况应该非常少见,必须格外小心,以避免产生跨站脚本 (XSS) 安全漏洞!

    【讨论】:

      【解决方案3】:
      import { Component } from '@angular/core';
      import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
      
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
      })
      export class AppComponent  {
      
        question = "How are __ doing today ?. I'm doing __.";
      
        constructor(private _sanitizer: DomSanitizer){}
      
        replaceFillBlanks(question){
            var $inputBox = '<input type="text" name="fillBox"/>';
      
            // if you'll replace any other string except text box this will work fine. 
            //var $inputBox = 'hi';
      
            let q = question.replace(/__/g,$inputBox);
            console.log(q);
              return this._sanitizer.bypassSecurityTrustHtml(q);
          }
      }
      

      参考:Inject <input> in innerHTML angular 2

      【讨论】:

        猜你喜欢
        • 2017-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-05
        • 2019-04-03
        • 2015-11-04
        • 1970-01-01
        相关资源
        最近更新 更多