javascript - 为什么我不能使用 <template> 作为 angular2 组件模板?

标签 javascript templates angular angular2-template angular2-directives

更新

显然在使用 <template> 时阅读innerHTML将返回小写的所有属性。 Angular2 不会理解ngforngif从 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它提示 ngModelngForOf不是已知的 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/

相关文章:

javascript - Typescript 的类型 "Property ' 上不存在错误 'IAugmentedJQuery' datepicker'

javascript - jQuery 在悬停时在链接上添加背景颜色,当鼠标悬停子菜单时背景保持不变?

c++ - 如何让部分模板与子类一起使用

angular - Auth 类型上不存在属性 'subscribe'

javascript - ionic 2 : Runtime Error Uncaught (in promise): TypeError: Cannot read property 'nav' of undefined

javascript - 如何从网站发送电子邮件?

javascript - 对象解构在 Promise 中解析和拒绝

c++ - 插入通用容器不起作用

c++ - 无法从 'Node<T> *' 推断出 'int' 的模板参数

Angular 2 模板驱动表单——验证总结