Angular class requires multiple class members and validators for MatSelection List to be bound with Formbuilder

Could you please guide me on how to connect the Google Angular Materials mat-selection-list with the FormBuilder? We have the following class and are attempting to utilize Reactive Form Builder for this purpose. While we are aware of how to link data classes with NgModel, we are seeking information on binding them to the actual form builder itself. What steps should be taken in order to achieve this with mat-selection-list?

class product{
    productId: number;
    productCode: string;
    productDescription

private formBuilder: FormBuilder,  ) {
    products: this.fb.array([])
}

In addition, what validation criteria are necessary as follows:

'product': this.formBuilder.group({
  'productId': [null, [Validators.required]],
  'productCode': [null, [Validators.required, Validators.maxLength(50)]],
 'productDescription': [null, [Validators.required, Validators.maxLength(255)]]
})

<mat-selection-list #productList class = "selectionlist" [(ngModel)]="selectedOptions" (selectionChange)="productChangeEvent($event,productList?.selectedOptions.selected)">
    <mat-list-option *ngFor="let product of products">
    {{product.productDescription}}
    </mat-list-option>
</mat-selection-list>

This pertains to a multiple selection form.

I have been searching for more information on this topic, Binding an Angular Material Selection List

Answer №1

Take a look at this example below. In your .ts file

testForm: FormGroup;
pets: { type: string; sound: string; }[];

constructor(private fb: FormBuilder){
this.testForm = this.fb.group({
  choices: [null]
});
 this.pets = [
  { type: 'Dog', sound: 'Woof!' },
  { type: 'Cat', sound: 'Meow!' },
  { type: 'Bird', sound: 'Tweet tweet!' },
  { type: 'Rabbit', sound: 'Hop hop!' },
];
}

In your HTML file

<form [formGroup]="testForm">
  <mat-form-field>
    <mat-label>Favorite pet</mat-label>
    <mat-select formControlName="choices" required (ngModelChange)="onChange()">
      <mat-option>--</mat-option>
      <mat-option *ngFor="let pet of pets" [value]="pet">
        {{pet.type}}
      </mat-option>
    </mat-select>
   </mat-form-field>
</form>

To retrieve the selected value in the form field from your .ts file

 onChange() {
console.log(this.testForm.value.choices);
}

https://i.sstatic.net/gVKmr.png

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

Insert an ellipsis within the ngFor iteration

I'm currently working with a table in which the td elements are filled with data structured like this: <td style="width:15%"> <span *ngFor="let org of rowData.organization; last as isLast"> {{org?.name}} ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...

Leveraging Firestore Errors within Cloud Functions

Is it possible to utilize the FirestoreError class within Firebase cloud functions? The goal is to raise errors with a FirestoreError type when a document or field is not found in Firestore: throw new FirestoreError(); Upon importing FirestoreError using ...

Using dynamic imports to enhance code by adding the `.at()` function can lead to errors in the process

Below is the content of my .tsconfig configuration file: { "compilerOptions": { "target": "es6", "baseUrl": "./src", "lib": ["dom", "dom.iterable", "esnext&q ...

When an event is triggered in Angular Component, the object is not properly defined in the handler causing errors

While experimenting with createjs and angular, I encountered an issue when trying to update my stage after an image loads. It seems like there might be a problem related to Angular in this situation. Upon completion of the load event on the Bitmap object a ...

Can someone guide me on incorporating static methods into a Mongoose model using TypeScript for Mongoose version 5.11?

When using Mongoose 5.10, I implemented static methods in my Mongoose models with the following pattern: import { Schema, Document, Model, Connection } from "mongoose"; import { v4 } from "uuid"; export interface IFoo extends Document ...

What sets apart gulp and webpack in an Angular 2 environment?

I've created a compact project that requires performance testing. For development, testing server and deployment of the Angular 2 app on IIS, which tool is more efficient - Webpack or Gulp? What are the key differences between Gulp and Webpack? ...

The Angular application is receiving a 404 error when trying to access the .NET Core

Having trouble calling a method in the controller via URL, as I keep encountering a 404 error. What could be the issue? API Endpoint: http://localhost:5000/Home/HomeTest /*.net core web-api*/ namespace MyApp.Controllers { Route("api/[controller]") ...

Angular has got us covered with its latest feature - combining Async Await with an EventListener

I have been facing this issue for the past day and need help creating a specific scenario: <img [src]="userdp | async" /> In my component.ts file, I want to include only this line: this.userdp = this._userService.getUserDp(); Here is the ...

What are the steps to utilize a personalized validation access form within a component?

I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly. Here is my template: <form class="forms-sample" #f="ngForm" (ngSubmit)="onS ...

Restricting types does not appear to be effective when it comes to properties that are related

I am working with a specific type that looks like this: type Props = { type: 'foo'; value: string; } | { type: 'baz'; value: number; }; However, when using a switch statement with the type property in TypeScript, the program in ...

Tips for generating a list in Angular2 based on previous selections

import { Component } from '@angular/core'; export class Superhero { name: string; } const SUPERHEROES: Superhero[] = [ { name: 'GK-1' }, { name: 'GK-2' }, { name: 'GK-3' }, { name: 'GK-4&ap ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

Jest may come across test suites, but it discreetly disregards the individual tests

Having encountered an issue with Jest testing in a Nuxt/Vue v2 project, I found that after making some changes, the tests were no longer running. The unit tests were either passing or failing initially, but suddenly stopped running altogether. ----------|- ...

Establishing the initial state within the constructor of a React Component utilizing a generic state

I have encountered an issue with React and Typescript. I am working on a component that utilizes two generics for props and state. interface Props { foo: string; } interface State { bar: string; } class Foo< P extends Props = Props, S e ...

Creating a Component with a flexible template: (Using transclusion and an inline template)

Trying to come up with a solution for creating a component that can work with dynamic template strings and access local variables within the template has proven to be quite challenging. No matter what approach I take, I always seem to struggle with getting ...

Passing asynchronous data from method1 to method2 without impacting the functionality of the script responsible for fetching the asynchronous data in method1

When working with TypeScript, I encountered an issue while trying to invoke an external script called SPCalendarPro within a private method that asynchronously fetches data. The script is invoked in the following manner: private _getSPCalendarPro() { con ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

Can Angular Material allow for unique CSS styling on each component?

As stated in the Angular Material Documentation, it is necessary to include the entire theme in order for the framework to function properly. This entails styles for all components. However, I am creating a component library and only pulling specific comp ...