【问题标题】:How to manage html logic in a separate file如何在单独的文件中管理 html 逻辑
【发布时间】:2016-11-06 10:11:17
【问题描述】:

我有一段 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 将相应地呈现数据,有人可以分享一个简单的例子来说明如何做到这一点基于我的代码?

谢谢!!

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

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

    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>
    

    【讨论】:

      【解决方案2】:

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


      当您想有条件地显示 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'}; 
      
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-09
        • 2012-04-16
        • 2019-07-09
        • 2022-06-17
        • 1970-01-01
        相关资源
        最近更新 更多