2016-11-06 73 views
2

我有一段HTML代碼,負責根據一定的條件下呈現的清單:如何在一個單獨的文件管理HTML邏輯

<!-- Show list only if there are more than 5 results --> 
     <div list.numberOfResults > 10"> 
      <b>Name: </b>{{list.name}} <b>ID: </b>{{list.id}} 
      <b>Country: </b>{{list.country}} 
     </div> 

<!-- Show list only if there are less than 10 results --> 
     <div list.numberOfResults < 10"> 
      <b>Name: </b>{{list.name}} <b>ID: </b>{{list.id}} 
      <b>Country: </b>{{list.country}} 
     </div> 

現在,我也有一些可選參數(list.country )所以我需要檢查它是否以前不空。

我相信有一種方法可以將此邏輯用於此HTML文件之外並創建一個可響應邏輯的文件,並且html將相應地顯示數據,有人可以分享一個簡單的示例基於我的代碼完成?

謝謝!!

回答

0

由於有兩個組件,您可以讓他們在一個單獨的文件,如姓名

component.html 

然後你就可以在導入的index.html像

<link rel="import" href="component.html" > 

或者你可以抓住從特定部分像

... 
    <script> 
    var link = document.querySelector('link[rel="import"]'); 
    var content = link.import; 

    // Grab DOM from component.html's document. 
    var el = content.querySelector('.component'); 

    document.body.appendChild(el.cloneNode(true)); 
    </script> 
</body> 
0

DEMO:https://plnkr.co/edit/6atoS1WOK5RzKSmNeR8n?p=preview


您可以使用ngSwitch當你想顯示HTML pieces有條件,

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div [ngSwitch]="list.numberOfResults>10">  // here 

     <div *ngSwitchCase ="true">     // here 
      <b> Template1 </b><br> 
      <b>Name: </b>{{list.name}} <br> 
      <b>ID: </b>{{list.id}} <br> 
      <b>Country: </b>{{list.country}} 
     </div> 


     <div *ngSwitchCase ="false">     // here 
      <b> Template2 </b><br> 
      <b>Name: </b>{{list.name}} <br> 
      <b>ID: </b>{{list.id}} <br> 
      <b>Country: </b>{{list.country}} 
     </div> 

    <div> 
    `, 
}) 
export class App { 

    list={numberOfResults:2,name:'myList',id:1,country:'USA'}; 

} 
相關問題