简体   繁体   English

在Angular 2中同时使用两个指令的有效方式

[英]Efficient way of using two directives at the same time in Angular 2

I'm new to Angular 2 and here is my code 我是Angular 2的新手,这是我的代码

<ng-container *ngIf="pageOrSearch"> 
    <div *ngFor="let feed of feedsPage">
        <font color="#8b0000"><u>Title: </u></font><strong>{{feed.title}}</strong><br>
        <font color="#8b0000"><u>PubDate: </u></font>{{feed.pubDate}}<br>
        <font color="#8b0000"><u>Link: </u></font><a target="_blank" href="{{feed.link}}">{{feed.link}}</a><br>
        <font color="#8b0000"><u>Description: </u></font>{{feed.description}}<br>
        <font color="#8b0000"><u>Category: </u></font>{{feed.category}}<hr>
     </div>
</ng-container>

<ng-container *ngIf="!pageOrSearch"> 
     <div *ngFor="let feed of feeds">
        <font color="#8b0000"><u>Title: </u></font><strong>{{feed.title}}</strong><br>
        <font color="#8b0000"><u>PubDate: </u></font>{{feed.pubDate}}<br>
        <font color="#8b0000"><u>Link: </u></font><a target="_blank" href="{{feed.link}}">{{feed.link}}</a><br>
        <font color="#8b0000"><u>Description: </u></font>{{feed.description}}<br>
        <font color="#8b0000"><u>Category: </u></font>{{feed.category}}<hr>  
     </div>
</ng-container>

This works fine, but is there any efficient way of using two directives at the same time in Angular 2? 这可以正常工作,但是在Angular 2中有没有有效的方式同时使用两个指令? I mean a conditional way of using theese two variables (feedsPage and feeds). 我的意思是使用这两个变量(feedsPage和feeds)的条件方式。

if pageOrSearch then feedsPage else feeds . if pageOrSearch then feedsPage else feeds

您可以使用三元运算符来避免在一个标记中使用两个指令,例如:

<div *ngFor="let feed of (pageOrSearch ? feedsPage : feeds)">

simple check the variable in your component first 首先简单地检查组件中的变量

result:any;
if(pageOrSearch){
   this.result=feedsPage;
} else {
   this.result=feeds
}

then in your html code: 然后在您的html代码中:

<ng-container> 
     <div *ngFor="let feed of result">
        <font color="#8b0000"><u>Title: </u></font><strong>{{feed.title}}</strong><br>
        <font color="#8b0000"><u>PubDate: </u></font>{{feed.pubDate}}<br>
        <font color="#8b0000"><u>Link: </u></font><a target="_blank" href="{{feed.link}}">{{feed.link}}</a><br>
        <font color="#8b0000"><u>Description: </u></font>{{feed.description}}<br>
        <font color="#8b0000"><u>Category: </u></font>{{feed.category}}<hr>  
     </div>
</ng-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM