Show the new elements added to an array in Angular without the need to refresh the page

I'm facing an issue where data added to an array is not being displayed on the browser, even though I can see it in the console. How can I ensure that the newly added data shows up without refreshing the screen in Angular?

user.component.ts

UserData: User[] = [
    {
      id: 1,
      email: 'Mellie',
      firstName: 'Gabbott',
      lastName: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b767c7a7979746f6f2b5b72757f727a6f72767e6835787476">[email protected]</a>',
      role: 'Female',
      status: 'Support'
    },
    {
      id: 2,
      email: 'Mellie',
      firstName: 'Gabbott',
      lastName: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e9e3e5e6e6ebf0f0b4c4edeae0ede5f0ede9e1f7aae7ebe9">[email protected]</a>',
      role: 'Female',
      status: 'Support'
    },
  ];

 onEmpCreate(){
    var test: User = {
      id: 3,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aecfcccdeedacbddda80cdc1c3">[email protected]</a>',
      firstName: 'Jim',
      lastName: 'Rambo',
      role: 'Doctor',
      status: 'Active'
    };
    this.UserData.push(test);
    console.log(this.UserData);
  }

user.component.html

Hello
<table mat-table [dataSource]="UserData">
    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef> Id </th>
        <td mat-cell *matCellDef="let user"> {{user.id}} </td>
      </ng-container>

      ... // Rest of the table code

  </table>

  <button (click)="onEmpCreate()">Add User</button>

My goal is to have the newly added data from the array display in the table seamlessly.

Screenshot of table and console after clicking add user: https://i.sstatic.net/q9piy.png

Answer №1

Managed to find the solution by referring to the duplicate link provided in the comments: Angular + Material - How to refresh a data source (mat-table)

user.component.ts

dataSource = new MatTableDataSource<User>(this.dataService.UserData);

constructor(private dataService: DataserviceService) { }

onEmpCreate(){
    this.dataService.addUsers().subscribe((data: User[]) => {
      this.dataSource.data = data;
    });
  }

dataservice.service.ts

 UserData: User[] = [
    {
      id: 1,
      email: 'Mellie',
      firstName: 'Gabbott',
      lastName: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd2d8deddddd0cbcb8fffd6d1dbd6decbd6d2dacc91dcd0d2">[email protected]</a>',
      role: 'Female',
      status: 'Support'
    },
    {
      id: 2,
      email: 'Mellie',
      firstName: 'Gabbott',
      lastName: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c313b3d3e3e3328286c1c353238353d283531392f723f3331">[email protected]</a>',
      role: 'Female',
      status: 'Support'
    },
  ];

addUsers(): Observable<User[]>  {
    var test: User = {
      id: 3,
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6c7c4c5e6d2c3d5d288c5c9cb">[email protected]</a>',
      firstName: 'Jim',
      lastName: 'Rambo',
      role: 'Doctor',
      status: 'Active'
    };
    this.UserData.push(test);
    let ids = this.UserData.map((obj)=> {
      return obj;
    });
    
    return of(ids);
  }

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

Configuring a JavaScript calendar with custom margins

Having trouble selecting a date with the Bootstrap datepicker class. After running the snippet, the calendar appears below the textbox: <input type="text" class="form-control datepicker" name="due_date" id="due_date" onclick="calendar_up()" value="" pl ...

Guide on using timestamps in PHP

I am struggling to incorporate the current date and time of the SO-NUMBER that the user is entering. The issue I'm encountering lies within the IF..ELSE loop, it only updates one column in the database, which is the "samplerecived" column even if I ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

Automatically populate the next dropdown menu depending on the answer provided in the previous field

Can you help guide me in the right direction with 2 questions I have? If the answer to the first question is 1, then I would like the following answer to automatically be populated as Yes. Please assist me! <div class="field"> <!-- Number of Em ...

Run JavaScript on every website when the page loads

After loading all or specific pages in the browser, I am looking to run JavaScript code (predefined code). Are there any browsers and plugins/components that allow me to achieve this? The manual method involves opening the console (e.g. firebug) and execu ...

The mouseover and mouseleave functions remain active even during window resizing

I wish to create a dynamic menu that appears when hovering over a user, but only if the window size is above 977 pixels. Take a look at my code below: $(document).ready(function() { $(window).on("load resize", function(event){ var windowS ...

Issue with form.io: Custom component not displaying on the form

I'm having trouble implementing form.io with a custom component named MeComponent. Unfortunately, it doesn't seem to be rendering properly and I can't pinpoint what's missing. Here are the steps I've taken. app.module.ts import { ...

Combining the power of Node.js and Node-MySQL with Express 4 and the versatile Mustache

Currently, I am delving into the world of Node.js and encountering a bit of a roadblock. My focus is on passing a query to Mustache. Index.js // Incorporate Express Framework var express = require('express'); // Integrate Mustache Template En ...

Activate the audit command for the npm enterprise registry

I'd like to know how to activate the npm audit command in my npm enterprise registry. Whenever I attempt to run the npm audit command, I encounter the following error: { "error": { "code": "ENOAUDIT", "summary": "Your configured registry ( ...

generate dynamic custom headers in an express application for accessibility by an Angular application

https://i.stack.imgur.com/6jyNE.pngRecently, I have started using Express and despite my extensive research, I haven't been able to find a solution to my issue. The problem is that I am receiving headers in my Express app, but when I attempt to make t ...

HTML links remain enclosed in a box even after the code has been finalized

Hey there, I have written this code and for some reason, every link shared after it is displaying with a black background. I'm new to coding and can't seem to figure out what I'm doing wrong. Any help would be greatly appreciated. a:link, ...

Sass: Overcoming the challenge of the IE limitation on 4095 selectors per stylesheet

Hey there! Are you working on a Rails project with Sass & Compass? If you're using the Rails Asset Pipeline, check out this question. We're in the process of developing a large application with multiple use cases and various individually styled ...

Refreshing a HTML table by retrieving data from a session variable

I'm still learning the ropes when it comes to JSP, jQuery, and AJAX. I have a JSP page that utilizes a table populated with values from a List variable stored in session. Below is the code snippet: <table id="someData" class="display" width="95%"& ...

Tips for effectively documenting CSS on a extensive website

Our website is quite extensive, with numerous pages. As we've added more pages, the amount of HTML and CSS has also increased. We're wondering if there's an efficient way to document all of this information. For example, how can we easily de ...

What is the method for inserting line breaks in Django at particular characters?

How can I add line breaks after specific characters in my text? Check out this image: https://i.sstatic.net/bz1h1.png I need to insert line breaks after every 50 characters in the text shown in the image. Take a look at my HTML FILE: {% extends ' ...

After signing out, the function getRedirectResult in Firebase is being invoked

I'm a bit confused about some interesting behavior I've noticed while working with Firebase. Although I never used the older version, I believe getRedirectResult is a newer feature since they partnered with Google. Currently, I am using Vue.js a ...

I'm looking to create a JavaScript function that will extract each element from a div and then apply a corresponding CSS block to activate it

My goal was to create this function using Flask, but it seems that only JavaScript is capable of achieving it. This is my first attempt at coding it. Here's the code snippet: const navSlide2 = () => { const burger = document.querySelector(&apos ...

What are the steps for defining a package once and utilizing it across multiple pages?

Hello, I'm new to Next.js and I have a question regarding the code organization. In my project, I have two pages: PostList (index.js) and PostSingle ([postId].js). I want to implement a feature that allows users to switch between dark and light theme ...

The CSS provider for Gtk+3 is malfunctioning

I've been attempting to set an image as the background of a GtkBox using a CSS provider, and also customize the style of some label text, but no matter what I try, nothing seems to work. Below is the content of my custom.css file: GtkBox#Home_Princi ...

Using ajax for sending data is a breeze, but I am encountering trouble when attempting to receive data back from

I have a function that retrieves a value from an input and sends data through ajax to another PHP file. However, I am facing an issue where I cannot retrieve the result back from the PHP file even though I echo it in the ajax success function. <script&g ...