Learn how to display data from the console onto an HTML page using Angular 2

I am working on a page with 2 tabs. One tab is for displaying active messages and the other one is for closed messages.

  1. If the data active value is true, the active messages section in HTML should be populated accordingly.
  2. If the data active is false, then the closed messages section in HTML should be filled instead. How can I achieve this?

Below is the HTML code:

<mat-tab label="Active">
  <mat-icon for="search">search</mat-icon>
  <input type="search" name="search" class="search" placeholder="Company">
  <ul>
    <li *ngFor="let message of activeMessages" (click)="showMessage(message)" [class.activeShow]="message.id == message_id">
      <span>{{message.date}}</span>
      <img src="{{message.image}}" alt="img" />
      <p style="padding-top: 16px;">{{message.name}}</p>
      <p ><b>{{message.subject}}</b></p>
    </li>
  </ul>
</mat-tab>
<mat-tab label="Closed">
  <mat-icon for="search">search</mat-icon>
  <input type="search" name="search" class="search" placeholder="Company">
  <ul>
    <li *ngFor="let closemessage of closedMessages" (click)="closeMessage(closemessage)" [class.activeShow]="closemessage.id == message_idc">
      <span>{{closemessage.date}}</span>
      <img src="{{closemessage.image}}" alt="img" />
      <p >{{closemessage.name}}</p>
      <p ><b>{{closemessage.subject}}</b></p>
    </li>
  </ul>
</mat-tab>

In the TypeScript file, I have the following code:

this.service
        .getMessages()
        .subscribe(
          data => {
            this.messagesdata = data;
            console.log(data);
            if(data.active== true) {
              this.activeMessages = this.messagesdata
            }
          },error => {});
  }

Here's the output in the console:

https://i.stack.imgur.com/bA3ro.png

Answer №1

Here is the task you need to accomplish:

Once you receive the response, filter the messages into two categories - activeMessages and closedMessages and display them based on certain conditions

You should declare variables as this.message_show and when the tab is changed, ensure that the messages section appears correctly so that you can view the messages as desired.

Component:

this.service
    .getMessages()
    .subscribe(
        data => {
            this.messagesdata = data;
            let activeMsgs = data.filter(msg => msg.active == true)
            this.activeMessages = activeMsgs;
            console.log(this.activeMessages);
            if (this.activeMessages.length > 0) {
                if (!this.message_show) {
                    this.message_show = this.activeMessages[0];
                    this.message = true;
                    this.message_id = this.activeMessages[0].id
                }
            }
            let closeMsgs = data.filter(msg => msg.active == false)
            this.closedMessages = closeMsgs;
            if (this.closedMessages.length > 0) {
                if (!this.message_close) {
                    this.message_close = this.closedMessages[0];
                    this.message_idc = this.closedMessages[0].id
                }
            }
            console.log(this.closedMessages);
        }, 
        error => { }); 

Answer №2

Refine your service response by applying filters

.subscribe(
          data => {
            this.messagesdata = data;
            let activeMsgs = data.filter(msg => msg.active == true)
                                 .map(m => { return m.messages});
            this.activeMessages = [].concat.apply([], activeMsgs);

            let closeMsgs = data.filter(msg => msg.active == false)
                                 .map(m => { return m.messages});
            this.closedMessages = [].concat.apply([], closeMsgs);
         }

Answer №3

Using the json pipe allows you to easily display the value of data.

{{data | json}}

By using this method, you can view the data's value similar to how it appears in the console.

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

Is there a way to adjust the dimensions of my Angular npm slider?

This snippet shows the Angular code I came across this npm slider on npm.js Struggling to adjust the margin of the images as they are sticking, also unsure about modifying the size and other elements using https://www.npmjs.com/package/ng-image-slider. A ...

Setting up a project in TypeScript with Angular 2(+) and a Node/Express server is essential for successful

Searching for the optimal approach for a project similar to this: An Angular 2 (4) client coded in TypeScript A Node/Express backend also written in TypeScript Utilizing some shared (TypeScript) models accessible to both client and server code. Is it pr ...

Retrieve the interface property following the execution of the HTTP GET service

Having trouble accessing the array properties from my JSON file using the http get service. The goal is to display the Widget array on the web. service.ts: import { Http, Response, Headers } from '@angular/http'; import { Observable } from &apo ...

Implementing the TabView positioning at the top for IOS in Nativescript

Is it possible to place the TabView at the top on IOS rather than the bottom? ...

What is the correct method for updating RxJS to the most recent version?

While attempting to update to the most recent version of RxJS, I followed the instructions from this documentation: https://github.com/reactivex/rxjs However, I encountered these warnings: npm warn @angular/[email protected] requires a peer of rxjs@ ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

Having trouble resolving the npm ERR with @angular-devkit/[email protected]? Found the solution to fixing it by checking out @angular/[email protected] instead

When I try to update the local Angular CLI version, I keep encountering an error with this command: npm uninstall --save-dev angular-cli. (following instructions from this source) npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ER ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

Is it possible to convert a DynamoDB AttributeMap type into an interface?

Assume I define a TypeScript interface like this: interface IPerson { id: string, name: string } If I perform a table scan on the 'persons' table in DynamoDB, my goal is to achieve the following: const client = new AWS.DynamoDB.Documen ...

"An error occurred in Angular due to the absence of a defined user

Creating a variable boolean isEdit in Angular8 to differentiate between add and edit functionalities. Hello, I am looking to edit in angular8 by setting up a boolean variable isEdit for distinguishing between adding and editing. Greetings! Currently work ...

Encountering Typescript errors while compiling an Angular module with AOT enabled

I am currently in the process of manually constructing an Angular module with Webpack, opting not to use the CLI. While a normal build is functioning without any issues, encountering errors during an AOT build! Here's how my tsconfig.aot.json file ...

I'm diving into the world of Typescript and trying to figure out how to use tooltips for my d3 stacked bar chart. Any guidance on implementing mouseover effects in Typescript would be greatly

I am currently facing some issues with the code below and need guidance on how to proceed. I am new to this and unsure of how to call createtooltip. Any assistance would be greatly appreciated. The error message states that createtooltip is declared but n ...

Web-based API for authentication system using Ionic framework and token-based login

I am developing a photo-sharing app that requires a login system. However, when attempting to log in, an error occurs stating that the value is not found. I am able to retrieve the value in services but struggling to get the email and password in login.pag ...

The variable isJoi has been set to true but there is an error due to an unexpected

I am currently developing a NestJs backend on multiple machines. One of the machines is experiencing issues with the @hapi/joi package. When running the NestJs application in development mode on this specific machine, I encounter the following error: PS C ...

What is the best way to adjust the Directions route Polyline to the edge of the map canvas?

I am currently working on a project that involves direction mapping, and I need the directions to be displayed on the right side of the panel when rendered. Here is what I am currently getting: However, I do not want the directions to appear behind the pa ...

Tips on customizing the Nuxt Route Middleware using Typescript

I am working on creating a route middleware in TypeScript that will validate the request.meta.auth field from the request object. I want to ensure this field has autocomplete options of 'user' and 'guest': export default defineNuxtRoute ...

Loading the value of a Subject variable in an Angular 2 application using Typescript

I am currently developing an Angular2 application where I am loading data from a service into my component as a subject. public type1Choisi: any; constructor( public formeService: FormeService, ...) { this.formeService._type1.subscribe(type1 => ...

Tips for implementing dynamic properties in TypeScript modeling

Is there a way to avoid using ts-ignore when using object properties referenced as strings in TypeScript? For example, if I have something like: const myList = ['aaa', 'bbb', 'ccc']; const appContext = {}; for (let i=0; i< ...

Each time the Angular children component is reloaded, the user is redirected to localhost:4200

In my Angular project, I encounter an issue with route parameters in children components. While navigating to these child components from the parent is seamless, reloading the child component causes the application to redirect to localhost:4200 and display ...