"Enhancing Angular's `mat-table` with bi-directional data binding

I'm running into an issue with the binding of mat-checkbox within a mat-table. The table's dataSource is a simple array of objects, each containing a boolean property for selection. However, I can't seem to get the two-way binding working properly as the selected value always returns false when the click event is triggered.

Here's a snippet of the code:

app.component.ts

   clients: Client[] = [
       { id: 1, name: `Client`, disabled: true, selected: false },
   ];

   onClientClick(client: Client) {
       console.log(client) // selected here is false
   }

app.component.html

<table mat-table [dataSource]="clients">
    <ng-container matColumnDef="client-name">
        <th mat-header-cell *matHeaderCellDef>header</th>
        <td mat-cell *matCellDef="let client">
            <mat-checkbox (click)="onClientClick(client)" [(ngModel)]="client.selected" [disabled]="client.disabled">
                {{ client.name }}
            </mat-checkbox>
        </td>
    </ng-container>
    <tr mat-row *matRowDef="let row; columns: displayedColumnsClients"></tr>
</table>

If anyone has any insights or solutions, please share. Thank you!

Answer №1

Initialize a MatTableDataSource as the DataSource.

clients= new MatTableDataSource<any>([{ id: 1, name: 'Client', disabled: true, selected: false }]);

Next,

<table mat-table [dataSource]="clients">
<ng-container matColumnDef="client-name">
<th mat-header-cell *matHeaderCellDef>header</th>
<td mat-cell *matCellDef="let client">
    <mat-checkbox (click)="onClientClick(client)"
    [disabled]="client.disabled" [checked]="client.selected">
    {{ client.name }}
    </mat-checkbox>
</td>
</ng-container>
<tr mat-row *matRowDef="let row; columns: displayedColumnsClients"></tr>

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

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

Is it possible to prevent casting to any by improving type definitions?

My query can be best elucidated with the following code snippet. The comments within the code aim to provide clarity on the nature of the question. type MediaFormats = "video" | "audio"; type IMediaContent<TType extends MediaFormats, TValue> = { ...

Trigger event in App.component.ts after child view initialization in Angular 8 and higher versions

I've been encountering an issue while trying to incorporate HubSpot page tracking into my Angular 8+ application. Currently, I'm tapping into the NavigationEnd event on my router within app.component.ts. The problem arises when each child compone ...

How can I decrypt a JWT token using Angular?

One of my current tasks involves decoding a jwt token that is provided by the API during the login process. Can anyone provide guidance on how to decode a jwt token in an Angular application? ...

Issue with Angular 2: Unable to locate the module '@angular/animations/browser'

I am currently attempting to install Angular2-Toaster (https://github.com/Stabzs/Angular2-Toaster). Initially, I successfully installed it using npm install angular2-toaster and was able to import it without any errors. However, I realized that I also need ...

Interactive Bootstrap 4 button embedded within a sleek card component, complete with a dynamic click event

I am trying to create a basic card using bootstrap 4 with the following HTML code. My goal is to change the style of the card when it is clicked, but not when the buttons inside the card are clicked. Currently, clicking on the test1 button triggers both ...

Turning a JSON string into interpolation within an Angular application

I received a JSON response that looks like this: { someText: "Order in {000} 12pm PST for early shipping"; cutofftime : "10000000" } What is the most effective way to replace the '{000}' with the dynamic value stored in &quo ...

How to Retrieve ViewChild Element from within Input Component in Angular 2

Currently, I am utilizing ViewChild to target a specific HTML element within an Angular 2 component. My goal is to access this element from an Input field, but I am struggling with the correct syntax to correctly target the element in question. Below is th ...

The process of deploying production-ready code using webpack and angular2

Currently, my Angular 2 code utilizes both webpack and grunt. During development, I rely on webpack-dev-server as a grunt task. When it comes to preparing the code for production deployment, I handle all minification tasks through Grunt which results in t ...

Is it possible to use NG-zorro and Angular material concurrently without encountering any conflicts?

I have encountered an issue with using both the ng-zorro and standalone components libraries in my project at the same time. Running the command "ng add ng-zorro" overrides all of my CSS, causing frustration. I've tried using standalone components ins ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Gathering user key event input for a duration of 2 seconds before resetting it

I need help implementing a feature where I can clear the user's input text after 500ms if they are entering characters consecutively. private userInputTimer; private userInputText = ''; private handleEvent(event: KeyboardEvent): void { if ...

When using Angular Reactive Forms with a number type control, the form will trigger a re-render when the

My Angular(v7) Reactive Form (or template-only form) is experiencing issues with re-rendering and validation on blur when using an <input> with type="number". The error feedback <div> next to the input contains a value suggestion button, whic ...

Modifying the default FilterSettings in ejs-grid: A step-by-step guide

Brand new to Angular and Material technologies, I recently created a grid following the instructions provided here. Below is the html template for the table: <ejs-grid #grid [dataSource]='data' allowFiltering='true' allowPaging=& ...

Tips for implementing multiple yield generators in redux-saga

Our redux-saga generator has multiple yield statements that return different results. I am struggling with typing them correctly. Here's an illustration: const addBusiness = function* addBusiness(action: AddBusinessActionReturnType): Generator< ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

The test window displays the Angular test component

During my test runs, I have noticed a strange occurrence. Components are appearing in the DOM near where the tests are being conducted. What's even more peculiar is that only one component is visible at a time. This phenomenon seems to occur with ever ...

Is it possible to utilize multiple useMutation hooks within a single component?

I'm curious about how to utilize multiple mutations in a component effectively. For instance, if I need to both create and update the same component, how can I achieve this? Here's an example: const [createUser, {data}] = useMutation(CREATE_US ...