0

I would like to separate some data. The situation is the next. A GET a JSON from my database and it has some different columns. For example: id, name, message, type. I would like to bind the data into different divs depending on the type content.

So I want to bind just those data's which contains the required strings ( like = 'connection error')

In my html file:

<div *ngFor="let data of data.data ">{{data.type}}</div> 

I want to show all the data from the JSON but on separated way. There are any way to give a requirement for the binding content ? Like this {{ data.type=''}} The requirement will be the type columns content. I try it like this:

<div *ngFor="let data of data.data; let type = connection error">
      {{data.message}} {{data.id}}
</div>

<div *ngFor="let data of data.data; let type = request error">
      {{data.message}} {{data.id}}
</div>

My TS is:

import { Component, OnInit, NgModule, Input} from '@angular/core';
import { ErrorsService } from './errors.service';

@Component({
  selector: 'app-errors',
  templateUrl: './errors.component.html',
  styleUrls: ['./errors.component.css'],   
})
export class ErrorsComponent implements OnInit {

    data: any = [];

    constructor(private errorsService: ErrorsService) {   }

    ngOnInit() {      
        this.errorsService.getAllErrors().subscribe(data => {
            this.data = data
        });  
    }    
  }

2 Answers 2

1

I'm not 100% sure what exactly it is you want but if you just want to do a simple check for the type you can do that with *ngIf or *ngSwitch.

<div *ngFor="let data of data.data;>
  <div *ngIf="data.type === 'connection-error'">
    There was a connection error
  </div>
  <div *ngIf="data.type === 'request-error'">
    There was a request error
  </div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

There are two approaches. If you want to solve it in the template you can create a custom pipe that filters entries with a certain type. Result would look something like this:

<div *ngFor="let data of data.data | type : 'connection error">
    {{data.message}} {{data.id}}
</div>

Here are the docs on how to setup a custom pipe: https://angular.io/guide/pipes

The second approach is TS-based. You can split them up in your TypeScript into 4 separate variables. This can be easily achieved with a Map.reduce() (or Map.forEach/filter&map as well)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.