What is the best practice for this kind of scenario?
I have a news feed (a repeated list of ion-cards) that I want to show in 2 different places. My thought was to create a child component that I could pull in wherever I needed. The child component would fetch the news items from our API and populate the template with the data so that I will only make the API call once instead of twice in separated components. Something like this:
Child component:
import { Component } from '@angular/core';
import { CRMNewsApi } from '../../../../api/CRM/eCom/crmShared';
@Component({
selector: 'news-feed',
templateUrl: 'news-feed.html'
})
export class NewsFeedPage {
newsItems: any;
constructor(private newsApi: CRMNewsApi) {}
getNews() {
this.newsApi.getNewsDetails().subscribe(data => {
this.newsItems = data;
});
}
}
Then the child view would be like this:
<ion-card *ngFor="let news of newsItems">
<ion-card-content>
<ion-card-title>
{{news.pageTitle | removeHtml | truncate : 68 }}
</ion-card-title>
<p class="red-text">
<i>{{news.created}}</i>
</p>
<p>{{news.pageText | removeHtml | truncate : 90 }}</p>
<ion-row>
<ion-col width-100 text-right>
<button ion-button clear small color="danger" icon-right (click)="newsSelected($event, news)">
Read More
<ion-icon ios="ios-arrow-dropright-circle" md="md-arrow-dropright-circle"></ion-icon>
</button>
</ion-col>
</ion-row>
</ion-card-content>
</ion-card>
In the parent - I tried using View child to access the method that gets the news from the component.
import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, LoadingController } from 'ionic-angular';
import { NewsItemPage } from '../../pages';
import { DomSanitizer } from '@angular/platform-browser'
import { NewsFeedPage } from '../../../shared/shared';
@Component({
selector: 'page-news-and-events',
templateUrl: 'news-and-events.html'
})
export class NewsAndEventsPage {
newsItems: any;
newsevents: any;
@ViewChild(NewsFeedPage) newsFeed: NewsFeedPage
constructor(
public navCtrl: NavController,
private loadingCtrl: LoadingController) {
//Inital selected segment
this.newsevents = "news";
}
ionViewDidLoad() {
let loader = this.loadingCtrl.create();
loader.present().then( () => {
this.newsFeed.getNews();
setTimeout(() => {
loader.dismiss()
}, 800);
});
}
newsSelected($event, news){
this.navCtrl.push(NewsItemPage, news);
}
}
This seems to pull in and show the data in the view. But the problem is - I have a set of 2 segments one for news and one for events (so would like to do same thing for events). When I first load the page - the news feed from child component is showing. When I change segment and back again, the child view has disappeared.
Any ideas why this is happening? OR if there is a better way I should be implementing a reusable component like this?