如何在一个单独的文件中管理html逻辑

How to manage html logic in a separate file

本文关键字:文件 管理 逻辑 html 单独 一个      更新时间:2023-09-26

我有一段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负责的文件,并相应地呈现数据,请有人分享一个简单的例子,说明如何根据我的代码做到这一点?

谢谢! !

由于有两个组件,您可以将它们保存在单独的文件中,如name

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>

DEMO:https://plnkr.co/edit/6atoS1WOK5RzKSmNeR8n?


当你想有条件地显示 HTML pieces 时,可以使用 ngSwitch

@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'}; 
}