Search code examples
javascripthtmlangularfetchionic4

pass variables from .ts to .html in ionic and angular


I am new to ionic 4 and angular and retrieving json data from http, in console I got the json perfectly, how can I pass this data from .ts to .html and show them like for each

enter image description here

home.page.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  constructor(private http: HttpClient) {
    this.http.get('https://mysite/reset-api.php').subscribe((response: any) => {
    console.log(response);
});
  }
}

home.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
 
  <ion-card>
    <ion-card-header>
      <ion-card-subtitle>  Title   </ion-card-subtitle>
      <ion-card-title>Card Title</ion-card-title>
    </ion-card-header>
  
    <ion-card-content>
      Keep close to Nature's heart... and break clear away, once in awhile,
      and climb a mountain or spend a week in the woods. Wash your spirit clean.
    </ion-card-content>
  </ion-card>
    




</ion-content>


Solution

  • Save your response from the API in a local variable in the TS file. It looks like your JSON response is an array. Each item appears to have an id and a title, although presumably each element of the array has other fields, too.

    You can use an *ngFor* to iterate over that variable from the TS file in your HTML template. And then in each loop, access fields of those array elements by name. For example, {{ item.title }} in the template would be replaced by the value of title for that array element.

    import { Component } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.scss'],
    })
    export class HomePage {
      dataArray;
      constructor(private http: HttpClient) {
        this.http.get('https://mysite/reset-api.php').subscribe((response: any) => {
        console.log(response);
        this.dataArray = response;
    });
      }
    }

    <ion-header>
      <ion-toolbar>
        <ion-title>
          Ionic Blank
        </ion-title>
      </ion-toolbar>
    </ion-header>
    
    <ion-content>
     
      <ion-card *ngFor="let item of dataArray">
        <ion-card-header>
          <ion-card-subtitle>{{ item.title }}</ion-card-subtitle>
          <ion-card-title>Card Title</ion-card-title>
        </ion-card-header>
      
        <ion-card-content>
          Keep close to Nature's heart... and break clear away, once in awhile,
          and climb a mountain or spend a week in the woods. Wash your spirit clean.
        </ion-card-content>
      </ion-card>
        
    
    
    
    
    </ion-content>