Home > Mobile >  Display api json data as ionic accordion
Display api json data as ionic accordion

Time:07-28

I have to display the api json data(nested object response) as an ion-accordion. How can I achieve it? Below is the code of the component.ts and service file

component.ts code:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.scss']
})
export class ViewComponent implements OnInit {

  users: any = [];
  constructor(private userdata: DataService) { }

  ngOnInit() {
    this.userdata.get().subscribe(data =>{
      this.users = [data];
      console.log(this.users);
    });
  }

}

service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  get():Observable<any>{
    return this.http.get<any>(' ');
  }
}

CodePudding user response:

It will depend on how "this.users" is formated. But you can use *ngFor to create your accordion.

For example if in your TS file you have users data :

users = [{name: 'Michel', isPremium: true}, {name: 'Jean', isPremium: true}, {name: 'John', isPremium: false}];

In your HTML file :

<ion-accordion-group>
 <ion-accordion *ngFor="let user of users">
   <ion-item slot="header">
     <ion-icon slot="start" name="star-outline" *ngIf="user.isPremium === true"></ion-icon>
    <ion-label>{{user.name}}</ion-label>
   </ion-item>
    <div slot="content">{{user.name}} is one of your user</div>
 </ion-accordion>
</ion-accordion-group>
  • Related