Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table?

I have successfully implemented my selection functionality, where I am able to mark a planet as "selected=true" on select (with all other planets set to false). Now, I am looking to modify the css-class (adding a red border) of the row which contains the object with the "selected" property set to true.

Here is a snippet of my HTML:

<table mat-table [dataSource]="planets" [trackBy]="trackById" class="mat-elevation-z8" id="planetList">

//all ng containers

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row [ngClass]="{'selectedPlanet': planet.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>
css:
.selectedPlanet {border-color: red;}

However, I am encountering an error in my console that says something like "ctx_r7.planet is undefined." I am unsure how to correctly use ngClass in this context on a mat table to modify the row. Can anyone provide some guidance on how to solve this issue?

Answer №1

In order to navigate safely, you must define your planet.

<tr mat-row [ngClass]="{'selectedPlanet': planet?.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>

If the planet is not defined, assume that the entry row has a selected property and use the row property to access any attribute.

<tr mat-row [ngClass]="{'selectedPlanet': row?.selected === 'true'}" *matRowDef="let row; columns: displayedColumns;"></tr>

Answer №2

To prevent errors related to reading undefined or null object properties in Angular templates, you can utilize the Safe Navigation Operator denoted by a question mark (?).

Revise your code as follows:

[ngClass]="{'selectedPlanet': planet?.selected === 'true'}"

It is recommended to ensure that template code relying on an object's presence should only render when the object is available. This can be achieved using the *ngIf directive.

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

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

Can I link the accordion title to a different webpage?

Is it possible to turn the title of an accordion into a button without it looking like a button? Here is an image of the accordion title and some accompanying data. I want to be able to click on the text in the title to navigate to another page. I am worki ...

Tips for halting the movement of marquee text once it reaches the center briefly before resuming animation

Is there a way to make text slide in, pause when centered, and then repeat the process? I'm looking for some help with this animation. Here is the code snippet: <marquee direction="left" id="artistslide"> <span id="currentartist">< ...

This particular JavaScript function is only designed to operate on the initial input box in the provided

I have a question regarding echoing rows of $data inside input boxes. I am using a JavaScript function that is supposed to copy the input value to the clipboard when the input box is clicked. However, I am encountering an issue - the function only works ...

What is causing the radio button's background color not to change after it is selected?

I've been searching and exploring various solutions, but I'm encountering some difficulties with the following scenario: There are a few restrictions: Cannot utilize Javascript or Jquery. Must be achieved using pure CSS. My objective is to chan ...

Troubleshooting Problem in Coursera's AngularJS Week 3 Exercise 4

Here's the issue I'm facing: After launching the index page with 'gulp watch', there's nothing visible on the screen. An error appears: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.12/$injector/modulerr?p ...

Exploring the possibilities of utilizing JavaScript within TypeScript

My dynamic javascript object holds all the resources (translation strings) for my app. Here's how it is structured: var ResourceManager = (function () { function ResourceManager() { var currentLanguage = $('#activeLanguage').htm ...

Interacting with a PNG file using a border radius in Internet Explorer 9 is causing issues with its transparency

Encountering an issue with IE9 where a white to gray gradient box appears around the transparent PNG on hover/selection. There is also a border radius applied to the thumbnail. Any ideas on how to fix this problem? Here is an example of the issue: https ...

Is there a way to disable the entire formgroup upon creation using FormBuilder?

While using the FormBuilder, I encountered an interesting challenge. For instance: formName = this.fb.group({ inputName: ['default value', Validators.required], // many other items }); (Example taken from: https://stackblitz.co ...

Tips for verifying that input is provided in a text field when the checkbox is marked

Can someone help me with validating a form where the user must enter data in a text field if they check a checkbox? I have JavaScript code for checkbox validation, but need assistance with text field validation. Thank you! $(document).ready(function () ...

Activate a side navigation bar in AdminLTE-3

I am using AdminLTE3 as my admin panel in Laravel, but I am facing an issue with the nav-item links not activating when clicked. Even though I have all the required assets for AdminLTE3 and used the starter.html file, the navigation items are not working p ...

Exploring Angular 2: Unveiling the secrets of lifecycle hooks in lazy loaded

Currently, I'm working on an application that involves lazy loaded Angular modules. I have a straightforward inquiry: Is there a way to detect an event once a module is loaded? For instance, similar to the OnInit lifecycle hook for components. I fo ...

The error message "Your session has expired" is displayed by the Wysiwyg

The WysiwygPro editor displays a dialog error message stating, "Your editing session has expired. This is usually caused by a long period of inactivity. Please re-load the page," when clicking on any controls such as Image, Media, Emoticon, etc. This iss ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

What is the best way to retrieve a cookie sent from the server on a subdomain's domain within the client request headers using getServerSideProps

Currently, I have an express application using express-session running on my server hosted at api.example.com, along with a NextJS application hosted at example.com. While everything functions smoothly locally with the server setting a cookie that can be r ...

Is it possible to adjust the color of the iOS status bar using NativeScript, Angular 2, and TypeScript?

I recently came across this npm package called NativeScript Status Bar, available at the following link: https://www.npmjs.com/package/nativescript-statusbar However, I'm facing an issue because I cannot use a Page element as I am working with Angul ...

Having difficulty setting up page titles in AngularJS

Using AngularJS, I am developing a web app that is not a single page application but all the code is contained in one file- index.ejs. The setup for my index.ejs file looks roughly like this: <head> <title> Main Page </title> </he ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

Is it secure to use a unique, static HTML/CSS website?

As a web developer, I am currently working on hosting a Wordpress-website for a client. However, my frontend development skills have improved significantly and now I feel inspired to create a simpler and more customizable version on my own. This website i ...

Exploring the Connection with JSON-server

While creating a simulated API using json-server, I encountered an issue with passing a query. When utilizing _expand, I am able to display the parameters of a relationship, but it doesn't seem to work when the relationship is nested within a child. ...