簡體   English   中英

我為什么不能使用 <template> 作為angular2組件模板?

[英]Why can't I use <template> as an angular2 component template?

更新

顯然,使用<template> ,讀取innerHTML將以小寫形式返回所有屬性。 截至此Beta 9版本,Angular2將不理解ngforngif並引發錯誤。 <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它將抱怨ngModelngForOf不是已知的本機屬性。

我將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM