Creating Dynamic ion-card Elements in Typescript by Programmatically Changing Values

Currently, I am working on a basic app that retrieves posts from the server and displays them as cards on the screen. At this early stage, one of my main challenges is figuring out how to dynamically add ion-card elements with changing content and headers using TypeScript. The snippet below shows how I am trying to achieve this:


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>";
    }

}

When I run the code and call the fillPost() function in the HTML file like so:

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

I encounter issues where the output doesn't display as expected. Here's an example:https://i.sstatic.net/KiKrF.jpg. Any guidance or assistance in resolving this problem would be greatly appreciated. Thank you.

Answer №1

In Ionic, it is not typical to use a for loop in the TypeScript file with HTML. Instead, you can directly utilize *ngFor 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 need to access variables from TypeScript code, you can do so using {{}}

For example:

{{Post Body}}

I can provide an example code snippet from my project where I retrieve soccer scores 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 fetch data from an API and receive a JSON response.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Utilizing a specialized ListItemAdapter that includes a delete button across multiple activities

I have successfully implemented a custom ListItem with a clickable ImageButton, thanks in part to the guidance provided in this response: how to use onClickListener method of Button on a ListView Now, I am facing a challenge where I have two separate act ...

Adding local images to Excel can be easily accomplished using Office Scripts

Hello, I've been attempting to replace Excel cells that contain image filepaths with the actual images themselves. I found an example in Office Scripts that shows how to insert images with online URLs but doesn't mention anything about inserting ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...

My Android Studio keeps getting stuck during the Gradle building process

After installing Android Studion on my Windows 10, I decided to create my first app ("Hello World") following the instructions from the Studio website. However, the process got stuck at the "Gradle Build" step, although my computer remained responsive. I s ...

Generating random values from an array within an ng-repeat loop

I need to add 4 different classes to a div within a ng-repeat. <li ng-repeat="post in posts"> <span class="color-RANDOM-VALUE">{{post.title}}</span> </li> After setting up the loop, it should display like this: <li> ...

Utilizing classes as types in TypeScript

Why is it possible to use a class as a type in TypeScript, like word: Word in the provided code snippet? class Dict { private words: Words = {}; // I am curious about this specific line add(word: Word) { if (!this.words[word.term]) { this.wor ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

Display real-time information in angular material table segment by segment

I need to incorporate service data into an Angular mat table with specific conditions as outlined below: If the difference between the start date and end date is less than 21 days, display 'dd/mm' between the 'start_date' and 'end ...

What is the best way to confirm the return type of a React.Component instance?

When working with TypeScript, there is a React Component called Cell: class Cell extends Component<void, void> { ... } Using it like this: <Cell /> The return type being received is JSX.Element. However, I want to make sure that the return ...

Displaying JSON Array in ListView - Merging

Although this question has been asked before, my code has some variations which are causing confusion regarding where I need to make changes. My goal is to extract data ("fest_name") and store it in an ArrayList called "festivals", and then display it i ...

Creating a personalized state object containing unresolved promises in React Native utilizing axios inside a custom React Hook

I'm currently in the process of creating a custom state within a custom Hook for React Native (non-Expo environment). The state I am working on looks like this: interface ResponseState { api1: { error: boolean; errorMsg?: string; ...

Having trouble integrating Cordova plugins into my project

I'm currently working on adding the buildinfo Cordova plugin to my project, which already has an Android platform integrated. All other required Cordova plugins have been successfully added. Could the issue be related to my Android version (6.4.0)? ...

Encountered an error while defining a Vue component using TypeScript with the @Prop decorator

When working with Vue.js and TypeScript, I usually use the following syntax: @Component({ props: ['uploadUrl'], }) export default class SelectionModal extends Vue { let x = this.uploadUrl // This variable `uploadUrl` is NOT resolve ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

Issues encountered when attempting to use Angular2 with SystemJs and typescript transpiler

I've encountered an issue with my TypeScript transpiler setup. My @angular component isn't loading, and I'm getting this error message: ZoneAwareError: "Error: core_1.Component is not a function Evaluating http://127.0.0.1:64223/app/app.c ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Utilizing React Native CheckBox within a FlatList Component:

I have integrated the CheckBox component from '@react-native-community/checkbox' in my project. However, I am facing an issue where I can only select each item once and I am unable to toggle it (change or re-toggle). import CheckBox from '@ ...

Having trouble with my phonegap app not allowing me to open any

I've just embarked on creating my first phonegap application using an HTML5 mobile website template. After deploying it, I noticed that the external links are not working within the app. Clicking on a link doesn't seem to do anything. To addres ...