jack miao
jack miao

Reputation: 1498

How to manage html logic in a separate file

i have a piece of html code that in charge of presenting a list based on certain conditions:

<!-- 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>

Now, I also have some optional parameter (list.country) so I need to check if its not empty before as well.

I believe there is a way to take this logic outside of this html file and make a file that is responsable of the logic and the html will present the data accordingly, can someone please share a simple example of how this can be done based on my code?

thanks!!

Upvotes: 2

Views: 87

Answers (2)

micronyks
micronyks

Reputation: 55443

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


You can use ngSwitch when you want to show HTML pieces conditionally,

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

}

Upvotes: 0

Hemel
Hemel

Reputation: 441

Since There are two component you can keep them in a separate file like name

component.html

Then you can import in index.html like

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

Or you can just grab specific portion from the file like

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

Upvotes: 0

Related Questions