Show the selected options in material checkboxes and automatically update the checkbox values when any of them is changed using Angular Material

I am brand new to Angular and I'm currently attempting to display all the data and update the value of a checkbox when it is checked or unchecked. Here's my code:

DatasetComponent.ts:

export class DatasetComponent implements OnInit {
  displayedColumns: string[] = ['id', 'sentenceWords','isHateSpeech', 'isIronic'];
  form: FormGroup;
  pageSizeOptions: number[] = [10, 25, 100, 500, 1000];
  sentences: MatTableDataSource<any> = new MatTableDataSource();

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

(... rest of the TypeScript code ...)
(... continuation of the TypeScript code ...)

and the HTML template:

<form [formGroup]="form">
      <div class="m-3">
        <table mat-table [dataSource]="sentences" matSort class="mat-elevation-z8">
          
          (... table columns definition ...)
        
        </table>
        <mat-paginator
        [pageSizeOptions]="pageSizeOptions"
        (page)="onPageChange($event)"
        showFirstLastButtons
      ></mat-paginator>
    </div>
</form>
(... rest of the HTML code ...)

Below is an error message that I usually encounter. Additionally, the checked values are not being displayed.

ERROR TypeError: Cannot read properties of undefined (reading 'get')
    at FacebookDatasetComponent_td_11_Template (facebook-dataset.component.html:20:27)
    at ReactiveLViewConsumer.runInContext (core.mjs:10407:13)
    at executeTemplate (core.mjs:10947:22)
    at refreshView (core.mjs:12468:13)
    at detectChangesInView (core.mjs:12632:9)
    at detectChangesInEmbeddedViews (core.mjs:12576:13)
    at refreshView (core.mjs:12492:9)
    at detectChangesInView (core.mjs:12632:9)
    at detectChangesInComponent (core.mjs:12608:5)
    at detectChangesInChildComponents (core.mjs:12646:9)

Here is a preview of the UI where the API returns JSON responses but the rows are not rendered correctly:

Despite using Reactive Forms, the rows are not rendering properly and the values are not shown as checked in the IsHateSpeech and IsIronic columns.

Answer №1

Consider rearranging your initForm() and loadCheckedValues() functions to ensure they have access to the data when they are called in onInit. It might be beneficial to move this code inside the getFacebookSentencesList subscription.

getFacebookSentencesList(page: number, pageSize: number, sortBy: string, sortDir: string, searchVal: string, body?: IFilterBody[]): void {
    this.loader.open('Loading data...');
    this.datasetService.getFacebookSentences(page, pageSize, sortBy, sortDir, searchVal, false).subscribe((response) => {
      this.sentences.data = response.data;
      this.paginator.pageIndex = response.currentPage - 1;
      this.paginator.pageSize = response.currentPageSize;
      this.paginator.length = response.totalElements;
      this.initForm();
      this.loadCheckedValues();
      this.loader.close();
    });
  }

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

Automatically assign the "Restricted" cursor to disabled fields within a dynamic form

Is there a method in Angular 6/7 that allows the cursor to change to "Not Allowed" when hovering over a disabled field in a reactive form? I prefer not to use CSS for this cursor change. Is there a way to achieve this through Angular alone? Currently, th ...

Utilizing Azure Active Directory for Authentication in Angular 13 and .NET Core Web API

I've set up a .NET CORE 6 Api as the backend and an Angular 13 frontend. I'm currently facing authentication issues with Angular using msal to call the protected .NET Core API, specifically the weatherforcast template. While I can successfully au ...

Passing an Array of Objects from a Child Component to a Parent Component in Angular

I have developed two components named parent and child. These components are linked in app.component.html. In the child component, I have an array of objects that I want to display in the parent component using @Output. My desired output is to show each ob ...

React: Premature exit, Fewer hooks executed than anticipated

I'm currently working on a chrome extension project where I'm trying to update an object based on a change in the current tab. However, I keep encountering an error that says I've rendered fewer hooks than expected. How can I resolve this is ...

Having trouble with your Ionic 2 Android release build getting stuck on a white screen post-splash screen?

Several weeks ago, I posted a question regarding this issue but unfortunately did not receive any response. So here I am posting again with a more specific problem. The Problem: 1.) I execute: $ ionic cordova build android --release --prod 2.) Then ...

Navigating to a component that also needs to redirect

I have a main feature (let's call it "main hub") that houses various sections. Within the "main hub" feature, I navigate to another section (let's call it "subsection") which also contains different subsections. In one of these subsections, call ...

Error encountered in Angular2 code due to a problem with inline templates

I'm grappling with the code below: import { Component } from '@angular/core'; @Component({ selector: 'character', template: `<h2 class="{{name}}">{{name}}</h2> <ul> ...

Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface. Here is the interface structure: export interface Interface{ ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Angular4 micro front-end development allows for a modular and scalable approach

Our application is made up of several services, with an edge service handling routing and load balancing for all requests to the individual services. The backend REST API is successfully deployed on each server, but we face a challenge with our single Ang ...

Is it feasible to define a custom Type in Typescript that accurately represents a Treeview structure?

Typescript is a TYPED superset of JavaScript that compiles into JavaScript, fine! It helps us to reduce some typos etc. I want to create an interface that will serve as an argument in a method. This interface needs to represent a treeview for parsing an ob ...

Ways to update a route's resolved information

Look at the route setup below: const routes: Routes = [ { path: '', component: AppComponent, resolve: { app: AppResolver }, children: [ { path: 'user/:uid', resolve: { user: U ...

I'm really puzzled as to why they would choose to export in this manner in React

I noticed that several files were exported in a similar manner, and I'm unsure why this specific method was chosen. Could there be any advantages or particular reasons for exporting them like this? index.ts export { default } from './Something& ...

What could be the reason for being unable to execute the 'ng' command even after a smooth

I have successfully installed Angular CLI 1.5 using the following command: C:\ANGULAR-WORKBENCH>npm install --global @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5c6c9cce5948b908b95">[email protect ...

Exploring the child element of the present DOM node within Angular

In my template, I have a code snippet similar to the one below: <button class="btn" > <audio src="mySourceFile.wav"></audio> </button> When the button is clicked, I want to play the audio object. Ideally, I would like to achieve ...

Typescript Array<String> useState Problem with IndexOf Function

Within my list component, I am required to maintain an array of strings for each element. These strings represent the checked status (via a checkbox) used to execute actions such as deletion. Additionally, I need to pass the links "themes/:id", which do no ...

Tips for showing an image through a button in Angular 4

Currently, I am in the process of creating a simple website and I have encountered an issue. When I click on a button to display an image, it works fine. However, when I click on another button to display a different image, the previous image remains visib ...

The error message "Can't resolve all parameters for CustomerService" is preventing Angular from injecting HttpClient

I have a customerService where I am attempting to inject httpClient. The error occurs on the line where I commented //error happens on this line. Everything works fine until I try to inject httpClient into my service. The error message is: `compiler.js: ...

Is there a way for me to reach my Store through a service?

Recently, I started using NgRx with effects to handle sending API requests. The setup is pretty straightforward - my API requests are managed in a service, and my effect utilizes this service. @Injectable({ providedIn: 'root' }) export class M ...

Understanding and processing HTML strings in typescript

I am currently utilizing TypeScript. Within my code, there is an object named "Reason" where all variables are defined as strings: value, display, dataType, and label. Reason = { value: '<ul><li>list item 1</li><li&g ...