Effective Approach to Implement Validation in Dynamic Display Column

I have a <mat-select> element in my Angular 7 project with an ngFor loop that displays rows from a table. I need to implement validation for the "type" column, allowing only one key to be selected at a time and preventing users from selecting "key" multiple times in the dropdown.

// HTML Code (Angular 7)
<!-- Column for Type-->
<ng-container matColumnDef="type">Type
<mat-header-cell *matHeaderCellDef mat-sort-header>Type</mat-header-cell>
<mat-cell *matCellDef="let element">
  <mat-select placeholder="Select Type" [(ngModel)]="element.type" (selectionChange)="checkTypeValidation(element,element.type)">
    <mat-option *ngFor="let type of typeColumn" [value]="type">
      {{ type }} 
      <div *ngIf = "element.type === "></div>
    </mat-option>
  </mat-select>
</mat-cell>
</ng-container>

The current code allows selection of any row as a key without enforcing any validation restrictions.

I aim to restrict the selection so that only one row can have the type of "key":

// TypeScript Code
typeColumn = [
    'None',
    'Time',
    'Segment',
    'Key',
    'Input',
    'Quantile'
];

This TypeScript snippet defines the available options for the Type column's dropdown menu, ensuring only a single row can be marked as a key.

Answer №1

My approach involves toggling the option between disabled and enabled based on user selection:

<mat-select placeholder="Type" (selectionChange)="changed($event)">
  

    changed(event){
      if(event.value.type == 'Key'){
         // Re-enable previous value
         if(this.previous[event.source.id] != undefined){
           this.typeColumn[this.previous[event.source.id]].allowed = true;
         }
         this.previous[event.source.id] = event.value.index;
         // Disable selected option
         this.typeColumn[event.value.index].allowed = false;
      }
    }
  

For a more in-depth look, check out the demo below:

You can use this code snippet to create your own solution:

View Full Demo

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

How to dynamically assign a value in a React datepicker component in a React application

Having troubles with react-datepicker? I encountered an issue where setting the value of react-datepicker from props caused it to either not show the value or display a 'wrong time format' error. Here is a snippet of the Datepicker code: this.sta ...

Ignoring setTimeout() function within forEach() in Angular leads to issues

I am currently working on the frontend development of a Web Application using Angular. My task involves saving data from an array into a database by making repeated API calls until all the array data is processed. I implemented the use of setTimeout() in ...

Angular 2: A guide to connecting Input with model property using getter and setter functions

I'm currently developing an Angular 2 web application. The model I have created consists of a few primary properties, along with other properties that are calculated based on those primary values. For each property in my model, I have implemented get ...

"Is it possible to add an entire object to formData in one

I am looking to send both an image list and product data to an ASP.net api using formData. I have successfully sent the images, but now I am struggling with appending the entire object. I have come across some methods in JS like JSON.stringfy(object) or Ob ...

"Encountering issues with the production build of angular2-flash-messages

I have integrated angular2-flash-messages into my Angular (4) application. I included it in app.module.ts as shown below: import { FlashMessagesModule } from 'angular2-flash-messages'; imports: [ FlashMessagesModule, ], Everything works f ...

There appears to be an issue with the compilation of the TypeScript "import { myVar }" syntax in a Node/CommonJS/ES5 application

In my Node application, I have a configuration file that exports some settings as an object like this: // config.js export var config = { serverPort: 8080 } Within another module, I import these settings and try to access the serverPort property: // ...

Is there a TypeScript equivalent to NSUserDefaults or SharedPreferences?

Just getting started with Angularjs-2.3 TypeScript and I have a specific scenario where I need to save the userId in the app so it can be accessed anywhere within the app. If I were developing for Android or iOS, I would typically use NSUserDefaults and S ...

Approach to Monitoring Notifications

Is there a best practice for managing notifications in an AngularJS application? When I mention 'notifications', I am referring to alerts that should be displayed to the user while they are logged into the app. My idea is to show the user any u ...

Transferring document via Angular 2

I'm trying to figure out how to send a file via POST in my web application. The server side is in Java and the client side is in Angular 2. On the server, I have this code: @RequestMapping(method = RequestMethod.POST, value = "/run/file") @ResponseBo ...

What is the process for configuring vue.config.js with typescript?

Just starting out with typescript and running into an issue while configuring vue.config.js const webpack = require("webpack"); module.exports = { plugins: [ new webpack.DefinePlugin({ __VUE_I18N_FULL_INSTALL__: true, __ ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

Steering clear of the generic Function type in React with TypeScript

Can anyone help me find a guideline that prohibits the use of "Function" as a type? myMethod: Function; I have searched but couldn't locate any information on this. Appreciate any suggestions :) ...

How to set return types when converting an Array to a dynamic key Object in Typescript?

Can you guide me on defining the return type for this function? function mapArrayToObjByKeys(range: [string, string], keys: { start: string; end: string }) { return { [keys.start]: range[0], [keys.end]: range[1] } } For instance: mapArrayToObj ...

What is the best way to upload a photo taken with the Android camera using FormData in Ionic/Angular?

Currently in the process of developing an Android app that allows users to capture and upload their picture to a PATCH API endpoint with the key 'avatar'. To accomplish this, I am utilizing the Cordova Camera along with the Advanced HTTP plugin ...

In what ways can enhancing the TypeScript type system with additional restrictions help eliminate errors?

Encountered issues while working on my TypeScript project due to errors in the type definitions of a library. The solution was to enable the strictNullChecks flag. It seems counter-intuitive that adding restrictions can eliminate errors, when usually it&a ...

Cypress with Typescript: Best ways to retrieve specific values from a dataTable

I am facing an issue with a data table that contains a list of states and messages which I need to validate in a particular scenario. Given user inputs "<state>" and sees "<message>" message | state | message | | Deac ...

Creating a Universal Resolver in Angular (2+) - A Step-by-Step Guide

I have a vision to develop an ultra-generic API Resolver for my application. The goal is to have all "GET" requests, with potential extension to other verbs in the future, utilize this resolver. I aim to pass the URL and request verb to the resolver, allow ...

How can a modal be opened in Angular 6 using only Bootstrap, without the use of Material?

In my left bar component, there is a button to open a modal. How can I make sure that the modal is opened when the button is clicked, but not within the component itself? ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Discover the simple steps to include row numbers or serial numbers in an angular2 datagrid

Currently, I am utilizing angular2 -datatable. Unfortunately, I am facing an issue where the correct row numbers are not being displayed in their corresponding rows. Whenever a user moves to the next page using the paginator, the datatable starts countin ...