Reputation: 1226
What am i trying to do?
I send a POST request to an API and using the response I dynamically create tabs. Here's the code for the following:
<div id="wrapper" class="container-fluid">
<ngb-tabset class="nav-fill">
<ngb-tab *ngFor="let category of categories" [title]="category.name" [id]="category.id">
<ng-template ngbTabContent>
<!-- Here we will have some content.
This content comes from the API which takes category.id as a param -->
</ng-template>
</ngb-tab>
</ngb-tabset>
</div>
I hope the code is clear.
The problem I'm facing is I'm not able to figure out how to get the content. Because I need the category.id to get the content, and somehow i have to attach a method which takes the category.id and performs the request and gets data.
So the user clicks on one tab, and some content is shown, and when he clicks on other tabs another set of content is shown which is all got through an API.
I found one method to do it. OnNgInit() I can get all the data required and then when the *ngFor runs I'll use the id reference to get the content. But I was looking for a more robust method to do it
Upvotes: 1
Views: 3847
Reputation: 418
Instead of calling all content data during ngOninit() method which is sometimes never used, you can attach (ngClick) event handler to your ngb tab like this:
<ngb-tab *ngFor="let category of categories" (ngClick)="selectedTab(category.id)" [title]="category.name" [id]="category.id">
<ng-template ngbTabContent>
<!-- Here we will have some content.
This content comes from the API which takes category.id as a param -->
</ng-template>
</ngb-tab>
and in your component, you can call your rest method to fetch the content for the tab:
@Component({...})
export class someComponent{
/* constructors private members bla bla */
selectedTab(id:int):any{
//call your service which makes http call to get content for your selected tab
getContent(id);
}
}
hope that answers your question!
Upvotes: 2