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

Update a DIV when ajax call is successful

I have a webpage with a specific heading: <div class="something"><? some php code ?></div> On this page, there is also an ajax function that performs a certain task: <script> $(document).ready(function () { $(document).ajaxSta ...

Unveiling RxJs: The secret to extracting the notifier value using the takeuntil operator

I have a straightforward Rxjs timer set up that runs until a notifier emits a signal, it's pretty basic so far. enum TimerResult = { COMPLETE, ABORTED, SKIPPED }; _notifier: Subject<TimerResult> = new Subject(); notifier$: Observab ...

Seamless animated loading gif as a looping background visual

Is there a way to find a GIF that can be used as a repeated background on an HTML element, creating the illusion of a seamless block? https://i.sstatic.net/5BKxW.gif (source: opengraphicdesign.com) I am looking for an 80x80 GIF that can be repeated as ...

Attempting to position an image in the middle-right of a column using bootstrap

After spending all day researching flexbox and vertical align, I still can't figure out how to align an image to the right in my bootstrap column with text wrapping around it on the left. Check out what I've tried so far here: https://codepen.io/ ...

Protractor failing to detect altered navbar post-login during e2e testing

During an e2e test run, the computer attempts to log in with a specified email and password using the Google login API. Upon successful login, the navbar switches from displaying "Login" to "Logout". I have been trying to wait for the Logout button to appe ...

typescript Parameter type dependency based on value is not functioning

interface AddDataRequest{ data:any } interface AddDataResponse{ id:string } interface ITest{ addData(json:AddDataRequest):Promise<AddDataResponse> removeData(json:AddDataResponse):Promise<boolean> } function testInterface<A e ...

Ways to eliminate undesired margin

I am struggling with formatting an HTML list into columns and I can't seem to remove the space between each column. It's frustrating because I want the list to display like rows, without any spacing or at least the ability to control the size of ...

The attribute aria-required is necessary for a radio group

When creating a required radio group, how should the aria-required="true" attribute be assigned? Specifically, I have multiple <input type="radio"> elements with the same name grouped under a <fieldset>. Should the aria-required be placed o ...

Place form at the center of the Bootstrap Modal

My question is, how can I center the entire form, including the input fields and labels, within the modal? Here is also a helpful Fiddle: http://example.com, although the snippet provided should work as well. <script src="https://example.com/bootstr ...

Retrieve data from the database and automatically populate all text fields when the dropdown value is modified

I need assistance with populating all textbox values based on the dropdown selection. The dropdown values are fetched using an SQL query. Here is the HTML Code: <select name="name" ID="name" class="form-control"> <opt ...

Implementing the react-i18next withNamespaces feature in Ant Design forms

I'm a newcomer to i18next and TypeScript, and I'm trying to translate an antd form using withNamespaces. export default withNamespaces()(Form.create()(MyComponent)); Encountering the following error: Argument of type 'ComponentClass< ...

Angular is throwing error TS2322 stating that the type 'string' cannot be assigned to the type '"canvas" while working with ng-particles

My goal is to incorporate particles.js into the home screen component of my project. I have successfully installed "npm install ng-particles" and "npm install tsparticles." However, even after serving and restarting the application, I am unable to resolve ...

Prevent dragging functionality after being dropped onto a droppable area

I am currently working on a drag and drop project and have encountered a minor issue. My goal is to disable the draggable item after it has been dropped onto the droppable area. I have created a function called disableDrag, but I am receiving an error in t ...

Having trouble with the Jquery Slider script?

I recently integrated a slider from into my website, following the installation instructions. However, I seem to be facing some conflicts with another script that controls animated div movements on the same page. Upon loading the page, all elements of th ...

Despite my attempts to force a repaint, the progress bar remained static during intensive tasks

My JavaScript method works fine in Chrome, taking about 2000 ms to iterate over ~200 inputs, insert values, and trigger onchange events. However, it's a different story in IE where it takes about 10000 ms. To show the progress of this process, I deci ...

Is there a way to retrieve the latitude and longitude values using a plugin and then make a web service call in Ionic with Angular 5?

I am currently trying to retrieve the latitude and longitude coordinates of a location by using geocode in Angular 5 within the Ionic framework. Once I have obtained the lat long, I intend to pass it to my service. The issue I am facing is that my service ...

NX combined with Nest.js and TypeORM, further enhanced with Webpack and Migrations

Recently, I embarked on a project using NX (Nest.js + Angular) and set up TypeORM for database configuration. While everything runs smoothly in "serve" mode, I found myself struggling with configuring migrations. In a typical Nest.js project, all files in ...

Adjust the transparency of an image preview using jQuery

Currently, I am working on creating a video gallery for a friend and I am experimenting with changing the thumbnail opacity using jQuery fade effect. While I can achieve this with CSS, I want to implement it with jQuery for a smoother transition. If you ...

Once the image is requested in HTML, three.js makes a subsequent request for the same image

This is a block of code. let image = new THREE.TextureLoader().load("http://odf9m3avc.bkt.clouddn.com/1493817789932.jpg") <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script> <img class='preLoad&apo ...

What is the best way to eliminate the blue outline around an image map?

On the landing page, I have a static background image and I've set up a clickable area using an image map. The issue is that when users click on the area, a blue border appears (see image below). I've tried several methods to remove this border b ...