[英]Why can't I use <template> as an angular2 component template?
更新
显然,使用<template>
,读取innerHTML
将以小写形式返回所有属性。 截至此Beta 9版本,Angular2将不理解ngfor
或ngif
并引发错误。 <script>
被视为文本片段,而不是DOM,这意味着属性保持不变。
此处: https : //groups.google.com/forum/#!topic / angular / yz-XdYV2vYw
Originial
采用以下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>
原因。 为什么会发生这种情况,我该如何解决?
<template>
标签仅由Angular 2 结构性指令 (例如内置的ngIf,ngFor,ngSwitch等)使用-它的用法在某种程度上与html5规范相似,因为它定义了存储的内容供以后使用。
结构指令前面的*
只是语法糖,它使我们可以跳过<template>
标记,而直接关注包含,排除或重复的HTML元素-您可以在此处了解更多信息。
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似乎已经发挥了作用。
角度处理<template>
标签本身,而不仅仅是将它们添加到DOM中。 如果将TemplateRef
注入到组件的构造函数中,则应获得对该模板的引用。
class MyComponent {
constructor(private tmplRef:TemplateRef) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.