Home > Enterprise >  Angular 11 - How to replace the output of the api response in the html
Angular 11 - How to replace the output of the api response in the html

Time:09-30

row.remarks has the output of 1 and 0. What I want to happen is that when the output is 0 I want to display it with the string "fail" and 1 is "passed" in the html. ` I'm 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;

    })
  }

CodePudding user response:

There are many options like having a custom pipe, but simplest would be to use the ternary operator in the template:

{{ row.remarks ? 'Passed' : 'Fail' }}

Another option would be to have a method in your class:

TS

getRemarksMessage(remarks: number) {
  return remarks ? 'Passed' : 'Fail';
}

HTML

{{ getRemarksMessage(row.remarks) }}

CodePudding user response:

Please try with below code

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

Also change in your interface remark feild like below,

remarks: number | string;

  • Related