Swapping the content of the API response with Angular 11 in the HTML

When the output of row.remarks is 1, I want to display it as "passed" and when it's 0, I want it to be displayed as "fail" in the HTML while using mat-table.

HTML

 <ng-container matColumnDef="remarks">
        <th class="font" mat-header-cell *matHeaderCellDef >Quiz Score</th>
        <td class="font" mat-cell *matCellDef="let row" >{{row.remarks}}</td>
      </ng-container>`

TypeScript

        interface IPost {
      id: number;
      quiz_id: number;
      quiz_title: string;
      difficulty: string;
      total_points: number;
      module_id: number;
      created_at: string;
      remarks: number;
      number_of_correct_answers: number;
      quiz_information: {
        quiz_title: string;
        difficulty: string;
        total_points: number;
      }
      users: {
        id: number;
        name: string;
    
      }

}



    getUserScoreByQuizID(quizID: number){

    this.dataService.getUserScoreByQuizID(quizID).subscribe(res=>{
      this.postsUser = res.UserScore;
      console.log(this.postsUser)

      this.dataSource = new MatTableDataSource(this.postsUser);
      console.log(res);

    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;

    })
  }

Answer №1

One way to handle this is by implementing a custom filter, but a more straightforward approach would be to utilize the ternary operator directly in the template:

{{ item.status ? 'Active' : 'Inactive' }}

Alternatively, you can also create a function in your component:

JavaScript

getStatusMessage(status) {
  return status ? 'Active' : 'Inactive';
}

HTML

{{ getStatusMessage(item.status) }}

Answer №2

Here is the suggested code for you to try:

this.dataService.getUserScoreByQuizID(quizID).subscribe(res => {
    res.UserScore.forEach(element => {
        element.remarks = element.remarks === 0 ? 'Fail' : 'Passed';
        this.postsUser.push(element);
    });
    console.log(this.postsUser)
    this.dataSource = new MatTableDataSource(this.postsUser);
    console.log(res);
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
})

You should also update your interface's "remarks" field like this:

remarks: number | string;

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

Leveraging local libraries with Angular

After setting up two local libraries: ng new my-library --create-application=false ng generate library core ng generate library shared The shared library utilizes the core library as shown below: import { CoreModule } from 'core'; @NgModule({ ...

Use ngFor to align items to the left in your design

I am working on a div element where I need to dynamically add inputs that should form a number with a specific format. To ensure the inputs start from the left, I have applied the justify-content-end class. HTML: <div class='row justify-content-end ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

The switchMap function in Angular does not trigger the async validator as expected

To ensure that the username entered by the user is unique, I am sending an HTTP request for every input event from the target element. It is important to debounce this operation so that only one HTTP request is made for X consecutive input events within a ...

The test session failed to launch due to an error in initializing the "@wdio/cucumber-framework" module. Error message: [ERR_PACKAGE_PATH_NOT_EXPORTED]

I added @wdio/cli to my project using the command 'npm i --save-dev @wdio\cli'. Next, I ran 'npx wdio init' and chose 'cucumber', 'selenium-standalone-service', 'typescript', 'allure' along w ...

What is the best way to integrate my Angular keycloak setup with an idphint attribute?

I have successfully integrated the angular keycloak adapter from https://www.npmjs.com/package/keycloak-angular to connect with our keycloak server. Currently, I am exploring the idphint attribute to redirect the request to a different identity provider. ...

Exploring Scroll Functionality for Inner Components Within Mat-tab

I am currently working on a small attendance project that involves using table components within mat-tab elements. However, I am facing an issue where the overflow from the table causes the entire component to scroll, when in fact I only want the table its ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

Encountering problem with React Typescript fetching data from Spring Data REST API: the error message "Property '_embedded' does not exist" is being displayed

I am currently working on a React application that utilizes Typescript to fetch data from a Spring Data REST API (JPA repositories). When I make a specific request like "GET http://localhost:8080/notifications/1" with an ID, my JSON response does not pose ...

Is it necessary to upload the node_modules folder to Bitbucket?

When uploading an Angular 2 app to Bitbucket, is it necessary to include the node_modules and typings folders? I am planning to deploy the app on Azure. Based on my research from different sources, it seems that when deploying on Azure, it automatically ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Capture stunning photos with Ionic Capacitor CameraPreview, where the camera is always front and center. Say goodbye to any

I'm currently working on developing a customized camera feature for a tablet application. One of the challenges I'm facing is getting buttons to float over the camera preview. Despite setting the isBack attribute to true, the camera preview remai ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

The preflight request for Ionic 7 fails the access control check, even though all origins, methods, and headers are permitted

Snippet; this.http.post(this.endpoint + "api/auth/signin", {"username": handle, "password": password}).subscribe(res => { // @ts-ignore if (res["status"] === "authorized") { loc ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

Preventing Repeated Form Submissions in Angular: A Helpful Guide

`Hello, I am new to Angular and I am struggling with a specific part of the form. People have been clicking the submit button multiple times quickly, causing the same information to be added repeatedly before it can be sent to the API. I have searched onl ...

What is the best way to transfer information from one column to another column with Office Scripts?

I'm in the process of automation with Microsoft Excel using Office Scripts, and I've hit a roadblock when trying to transfer data from one column to another. Specifically, I need to move the data from the Date column (D) over to the New_Date col ...

Angular with Firebase: How to ignore a field in a query

I am curious to see if my current structure is compatible with Firebase, or if I need to make adjustments. Let's take a look at an example using the "/rooms" endpoint, which contains an array of Room objects: export class Room { id: number; p ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...