2017-01-12 56 views
0

在两个不同的组件有限的数据例如如何显示在角2

我已在其中所有图像从JSON示出共享组件称为图像画廊制成。现在我在主页和图库页面中使用这个共享组件。在主页上,我想先显示8张图像,并在图库页面中显示所有图像。

共享组件

@Component({ 
selector: 'app-gallery', 
templateUrl: './gallery.component.html' 
}) 
export class GalleryComponent implements OnInit { 
//getting images data from my service 

} 

HTML是共享的组件是

<div class="col-md-3 col-sm-6" *ngFor="let image of gallery"> 
    <div class="gallery-img"> 
    <a href=""> 
     <img src="{{gallery.images[0]}}"> 
    </a> 
    </div> 
</div> 

主页的HTML组件

<app-gallery></app-gallery> //Here i want show 8 images only 

图库组件页

<app-gallery></app-gallery> // Here i want to show all images from gallery 
+0

你可以发布你的组件的代码? –

+0

什么是共享组件,它是什么选择器,它在哪里使用? –

回答

0

您可以在您的应用程序画廊组件创建输入属性:

@Input() images: any[]; 

,并传递任何阵列来自父组件的图像:

<app-gallery [images]="images"></app-gallery> 

或只传递前4个图像使用切片管:

<app-gallery [images]="images | slice:0:3"></app-gallery> 

这里的基本plunker这可能有助于了解如何做到这一点。

+1

使用'slice'管道的好处是只有当'images'数组发生变化时才调用它,而每次运行变化检测时会调用'.slice()'方法,这可能会非常昂贵。 –

+1

@GünterZöchbauer谢谢你,哇,不知道切片管道。很方便!将更新我的答案 –

+0

感谢您解释,它的工作。 – Sohail

1

也许你可以在自家的&图库页面中使用你的组件选择器,这两者都将具有不同的共享组件实例。

并且为了检测这个共享组件属于哪个组件,可以像下面那样传递字符串值作为输入值。现在

<shared_component [hostComponent]="homePage"></shared_component> 
<shared_component [hostComponent]="imageGallery"></shared_component> 

,共享组件里面,你可以决定是否hostComponent是“主页”然后应用管限制图像8别的不适用的管道。