【问题标题】:How do you display a literal {{ in Angular 2你如何在Angular 2中显示文字{{
【发布时间】:2017-05-24 07:08:07
【问题描述】:

我在 Angular2 rc 1 中有一个模板,我需要在其中显示来自不同语言的一段代码。该语言中有{{。

import {Component, Input} from '@angular/core';

@Component({
    selector: 'blue-box',
    template: `
        <div class="blue-box">
            <div class="blue-box-title">{{boxTitle}}</div>
            {{define "bob"}}This is the template bob{{end}}
            <span>
                <ng-content></ng-content>
            </span>
        </div>
    `,
    styleUrls: ['../css/blue-box.css'],
})
export class BlueBox {

    @Input() boxTitle: string;

    constructor() {
    }

}

如何让模板处理器将 {{ 视为文字字符串而不是模板表达式的开头?出现问题 在我需要文字 {{.

的 {{define "bob"}}

浏览器(chrome)控制台上的错误是:

EXCEPTION: Template parse errors:
Parser Error: Unexpected token 'bob' at column 8 in [
        {{define "bob"}}This is the template bob{{end}}
        ] in BlueBox@2:49 ("
    <div class="blue-box">
        <div class="blue-box-title">{{boxTitle}}</div>[ERROR ->]
        {{define "bob"}}This is the template bob{{end}}
        <span>
            <ng-content></ng-content>
 "): BlueBox@2:49

【问题讨论】:

    标签: angular


    【解决方案1】:

    使用 ngNonBindable

    示例:

    <div ngNonBindable> {{ I'm inside curly bracket }} </div>
    

    更新

    以上内容在 Anuglar 2 中有效,现在在 Angular 4 中有一个名为 DomSanitizer 的类,可用于在 HTML 中插入任何类型的代码作为文本。

    您可以从micronyks's answer 中检查此工作plunker

    【讨论】:

      【解决方案2】:

      ngNonBindable - 并不总是一种选择,您必须使用额外的 DOM 元素,实际上有更好的方法

      RC1 之后

      在下一个版本中,将提供一种自定义插值正则表达式 https://github.com/angular/angular/pull/7417#issuecomment-221761034 的方法。它已经合并,将在下一个版本中提供。

      RC1

      现在你可以做到这一点。转到 main.ts (或您执行 bootstrap 的其他文件)并添加此

      // some of your imports here
      import { Provider } from '@angular/core';
      import { Parser, SplitInterpolation } from '@angular/compiler/src/expression_parser/parser';
      import { Lexer } from '@angular/compiler/src/expression_parser/lexer';
      import { StringWrapper } from '@angular/platform-browser/src/facade/lang';
      import { BaseException } from '@angular/platform-browser/src/facade/exceptions';
      
      class Parser2 extends Parser {
        myInterpolationRegexp = /\[\[([\s\S]*?)\]\]/g; // <- CUSTOMIZATION
        constructor(public _lexer: Lexer) {
          super(_lexer)
        }
        splitInterpolation(input, location):SplitInterpolation {
          var parts = StringWrapper.split(input, this.myInterpolationRegexp);
          if (parts.length <= 1) {
            return null;
          }
          var strings = [];
          var expressions = [];
           for (var i = 0; i < parts.length; i++) {
            var part: string = parts[i];
            if (i % 2 === 0) {
              // fixed string
              strings.push(part);
            } else if (part.trim().length > 0) {
              expressions.push(part);
            } else {
              var exs = `Parser Error: Blank expressions are not allowed in interpolated strings at column ${this._findInterpolationErrorColumn2(parts, i)} in [${input}] in ${location}`;
              throw new BaseException(exs);
            }
          }
          return new SplitInterpolation(strings, expressions);
        }
        private _findInterpolationErrorColumn2(parts: string[], partInErrIdx: number): number {
          var errLocation = '';
          for (var j = 0; j < partInErrIdx; j++) {
            errLocation += j % 2 === 0 ? parts[j] : `{{${parts[j]}}}`;
          }
          return errLocation.length;
        }
      }
      
      bootstrap(AppComponent, [
        // add your custom providers array with out parser provider
        new Provider(Parser, { useClass: Parser2 })
      ]);
      

      现在您可以像这样编写模板

      <div>[[ title ]]</div>
      {{begin}} asdas {{#end}}
      <div>
        <div *ngFor="let item of list | isodd">
          [[ item.name ]]
        </div>
      </div>
      

      请注意,现在您不必将代码包装在 NgNonBindable 中

      更新:

      ngNonBindable 是一个糟糕选择的原因之一。

      这个例子会有很多不同的方式

      <div>{{ title }}</div>
      <div ngNonBindable>
        {{begin}}
        <button (click)="add()">add</button>  <!--- Will Explode!!! --->
        <div>
          <div *ngFor="let item of list | isodd">
            {{ item.name }}
          </div>
        </div>
        {{#end}}
      </div> 
      

      如果你使用 InterpolationRegexp - 一切都会正常工作(而且它少了一个 DIV)

      <div>[[ title ]]</div>
      {{begin}}
      <button (click)="add()">add</button>
      <div>
        <div *ngFor="let item of list | isodd">
          [[ item.name ]]
        </div>
      </div>
      {{#end}}
      

      【讨论】:

      • "After RC1" 插值正则表达式似乎是一个全局选项。当您只想显示一个原始绑定但应用程序的其余部分正常处理时,我不希望在这种情况下有帮助。
      • @GünterZöchbauer 请阅读更新。我同意在某些小情况下 ngNonBindable 更好。但总的来说 - 这不是一个很好的解决方案。
      • 如果您想与另一个使用{{}} 的框架集成,那么插值正则表达式肯定是更好的选择。如果您在 Angular 应用程序中有一些 sn-ps(如 Angular 代码示例),那么 ngNonBindable 可能是更好的选择。我假设使用非标准插值正则表达式不能再使用任何组件库(如 angular2-material),并且您的整个应用程序需要使用 [[]](例如)而不是 {{}} 构建。
      • @GünterZöchbauer 组件库的优点。完全同意。有时 InterpolationRegexp 也会把你搞砸。
      猜你喜欢
      • 1970-01-01
      • 2017-09-02
      • 2013-11-13
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多