简体   繁体   中英

How to Add ion-card with changing values programmatically in typescript?

I am building a simple app where i read some Posts from server and try to display the latest posts as cards in the screen . I am still in a very early stage and i am testing as to how to add ion-card elements with changed contents and headers with typescript ? my current code is like ths :

fillPost() {
    for (let i: number = 0; i < 10; i++) {


         this.postContainer += "<ion-card> "
            + "<ion-item> <h2 item-left> Name here </h2>"
            + "<p> Post Number : +"i+" </p> </ion-item> <ion-card-content>"
            + "<p> Post Body here </p> </ion-card-content>"
            +"<ion-row > <ion-col > <button ion- button icon- left clear small> "
            + "<ion-icon name= \"thumbs-down\" > </ion-icon>"
            + "< div > Report < /div>"
            + "</button>"
            + "</ion-col>"
            + "<ion-col center text-center>"
            + "<ion-note>"
            + "1h ago"
            + "</ion-note>"
            + "</ion-col>"
            + "</ion-row>"
            + "</ion-card>";

    }



}

and in my HTML file :

 <div [innerHTML]="postContainer">
 </div>

there is a button which called the fillPost() function as to test things out but the results looks like this :

http://imgur.com/a/z5XyW

please help me and thanks .

In Ionic it's not common to do the for loop in the ts file with html. You can use a *ngFor directly in the HTML

https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

 <ion-card *ngFor="let item of i">
  <ion-item>
    <h2 item-left> Name here </h2>
    <p> Post Number : {{item}} </p>
  </ion-item>
  <ion-card-content>
    <p> Post Body here </p>
  </ion-card-content>
  <ion-row>
    <ion-col> <button ion- button icon- left clear small>
            <ion-icon name= \"thumbs-down\" > </ion-icon>
            <div > Report < /div>
            </button>
    </ion-col>
    <ion-col center text-center>
      <ion-note>
        1h ago
      </ion-note>
    </ion-col>
  </ion-row>
</ion-card>

If you want to read variables from ts code. Use {{}}

fe

{{Post Body}}

i can show you an example code from my project I read some soccer scorings from the server

<ion-card *ngFor="let item of data">
  <ion-card-content>
    <div style="text-align: center">
      <p>{{item.HomeTeam}}</p>
      <p> <strong>{{item.HomeGoals}}:{{item.AwayGoals}}</strong> </p>
      <p>{{item.Away}}</p>
  </ion-card-content>
</ion-card>

TS: i load the api and get back a json

 ionViewDidLoad() {
  console.log("Standings Load", this.team)
   this._api.getData()
  .subscribe(d => this.data = d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM