【发布时间】:2016-03-22 22:23:38
【问题描述】:
更新
显然,当使用<template> 时,innerHTML 的读数将返回小写的所有属性。从这个 beta 9 版本开始,Angular2 将无法理解 ngfor 或 ngif 并引发错误。 <script> 被视为文本片段而不是 DOM,这意味着属性保持原样。
这里: https://groups.google.com/forum/#!topic/angular/yz-XdYV2vYw
原创
采用以下html和angular2 beta 9组件:
HTML 代码
<my-page>Loading...</my-page>
<script type="text/html" id="my-component-template1">
<select [(ngModel)]="SelectedType">
<option *ngFor="#someType of MyTypes" [selected]="SelectedType == someType" [value]="someType">{{someType}}</option>
</select>
</script>
<template id="my-component-template2">
<select [(ngModel)]="SelectedType">
<option *ngFor="#someType of MyTypes" [selected]="SelectedType == someType" [value]="someType">{{someType}}</option>
</select>
</template>
JS 代码
var myComponent =
ng.core.Component({
selector: 'my-page',
//complains if i use #my-component-template2
template: document.querySelector('#my-component-template1').innerHTML
})
.Class({
constructor: function () {
var self = this;
self.MyTypes = ['first', 'second'];
self.SelectedType = self.MyTypes[0];
}
});
document.addEventListener('DOMContentLoaded', function () {
ng.platform.browser.bootstrap(myComponent);
});
如果我使用my-component-template1,它可以正常工作,但如果我选择my-component-template2,它会抱怨ngModel 和ngForOf 不是已知的本机属性。
我测试了一个div 作为模板,显然这也不会出现同样的错误。所以问题是,如果模板是 DOM 的一部分,为什么会破坏?此外,我真的不想使用script text/html hack。假设这就是在 html5 规范中添加 <template> 的原因。为什么会发生这种情况,我该如何解决?
【问题讨论】:
标签: javascript templates angular angular2-template angular2-directives