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}}