更新
显然在使用 <template>
时阅读innerHTML
将返回小写的所有属性。 Angular2 不会理解ngfor
或ngif
从 beta 9 版本开始并抛出错误。 <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
不是已知的 native 属性。
我测试了div
作为模板,显然这不会出现相同的错误。所以问题是,如果模板是 DOM 的一部分,为什么会破坏呢?此外,我真的不想使用 script text/html
黑客。假设这就是原因<template>
被添加到html5规范中。为什么会发生这种情况以及如何解决它?
最佳答案
<template>
标签仅由 Angular 2 使用 structural directives (如内置的 ngIf、ngFor、ngSwitch 等) - 它的使用在某种程度上与 html5 specification 类似。因为它定义了存储供后续使用的内容。
*
结构指令前面只是语法糖,它允许我们跳过 <template>
标签并直接关注我们要包含、排除或重复的 HTML 元素 - 您可以阅读有关它的更多信息 here .
Angular 2 文档中的一个示例展示了这一点:
<!-- Examples (A) and (B) are the same -->
<!-- (A) *ngIf paragraph -->
<p *ngIf="condition">
Our heroes are true!
</p>
<!-- (B) [ngIf] with template -->
<template [ngIf]="condition">
<p>
Our heroes are true!
</p>
</template>
目前,我不确定是否有一种方法可以像 AngularJS 1 中那样定义内联 Angular 2 HTML 模板。正如您所说,您的hack似乎发挥了作用。
关于javascript - 为什么我不能使用 <template> 作为 angular2 组件模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36166380/