Reputation: 9230
I have some data that I have called from an external api. Now what I want to do is have a button on my page that iterates through the data..
so.. for example say I have a page on my site that has a title and some text which comes from the api and the data im recieving back from the api is
{
fields: {
title: 'title 1',
text: 'this is some text'
}
},
{
fields: {
title: 'title 2',
text: 'this is some more text'
}
},
now I want the first item to be inserted into the title div and then the text inserted into the text div
so something like..
<div class="title">{{response.fields.title}}</div>
<div class="text">{{response.fields.text}}</div>
then when I click a next
button on my page I want the title and text to update to the second item so title 2
and text
I'm not 100% how I would do something like this..
So my set up is as follows
contentful.service.ts
@Injectable()
export class ContentfulService {
private cdaClient = createClient({
space: CONFIG.space,
accessToken: CONFIG.accessToken
});
constructor() { }
getProgramItems(query?: object): Promise<Entry<any>[]> {
return this.cdaClient.getEntries(Object.assign({
content_type: CONFIG.contentTypeIds.programItems
}, query))
.then(res => res.items);
}
}
app.component.ts
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { ContentfulService } from '../contentful.service';
import { Entry } from 'contentful';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
// define private class properties
private programItems: Entry<any>[] = [];
constructor(
private contentfulService: ContentfulService
) { }
ngOnInit() {
this.contentfulService.getProgramItems()
.then(programItems => this.programItems = programItems)
.then(() => {
console.log(this.programItems);
});
}
so basically I want to have the title and text of each program item to update the title and text div on the page on a button click, I thought about using a ES6 generator but Im not sure how I would use it in this case.
Any help would be appreciated
Thanks
Upvotes: 0
Views: 631
Reputation: 6455
<div class="title">{{currentItem.title}}</div>
<div class="text">{{currentItem.text}}</div>
<button (click)="goToNext()">Next</button>
public counter: number = 0;
public currentItem: Entry<any>;
goToNext() {
if (this.counter > this.programItems.length) this.counter = this.programItems.length;
this.currentItem = this.programItems[this.counter];
this.counter++;
}
You could try something like above.
Assuming you have got your programItems
array back from the service and all populated correctly, then you could use a counter as the array index and increment it every time you click the Next button.
Upvotes: 3