Validation error not displaying in Angular Material's mat-chip-list with input component

I'm currently encountering a peculiar problem with using mat-chip-list with inputs. My form group consists of two form controls: contacts and name.

this.form = this.formBuilder.group({
    name: ['', [Validators.required]],
    contactIds: ['', [Validators.required]]
})

The layout of this form is as follows:

<mat-form-field #contactsChipList>
    <mat-chip-list>
        <mat-chip *ngFor="let contact of contacts" [removable]="removable" (remove)="removeChipListItem(contact)">
            {{ contact.name | titlecase }} {{ contact.surname | titlecase }}
        <mat-icon matChipRemove *ngIf="removable"></mat-icon>
        </mat-chip>
        <input [matChipInputFor]="contactsChipList" placeholder="Contacts" formControlName="contactIds" />
        <mat-error *ngIf="form.hasError('required', 'contactIds')">This field is required</mat-error>
    </mat-chip-list>
</mat-form-field>

Issue: When I clear all the elements from the input field, the parent form (formGroup) is flagged as invalid, but the error property of the formGroup remains empty. As a result, the error message is not displayed.

Alternative Attempt: However, when I utilize a standard input element with a matInput attribute instead of a mat-chip-list, the error is properly shown upon clearing the field.

Here is the markup for this scenario:

<div class="form-group">
    <mat-form-field>
        <input matInput placeholder="Contacts" formControlName="contactIds" />
        <mat-error *ngIf="form.hasError('required', 'contactIds')">This field is required</mat-error>
    </mat-form-field>
</div>

Assumption: I suspect the issue is related to the mat-chip-list element. I have attempted to investigate the following:

@Input()errorStateMatcher: ErrorStateMatcher
but I am unsure how to implement it. Unfortunately, my online searches have not been very helpful.

Has anyone else faced a similar problem? Feel free to ask for further clarification.

Answer №1

You need to include the validator within the <mat-chip-list> element to prevent adding invalid items. Here's how you can do it:

Component:

export class ExampleComponent {
    items = [];
    emailFormControl = new FormControl('', [Validators.email]);

    addItem(event) {
        if (this.emailFormControl.valid) {
            items.push(event.value)
        }
    }

    .
    .
    .
}

Template:

<mat-form-field>
    <mat-chip-list [formControl]="emailFormControl">
        .
        .
        .
    </mat-chip-list>
</mat-form-field>

Edited: It appears that you are using a FormGroup. Make sure to add ngDefaultControl to the mat-chip-list element. You can find more information here.

<mat-form-field>
    <mat-chip-list ngDefaultControl [formControl]="form.controls.contactIds">
        .
        .
        .
        <mat-error *ngIf="form.controls.contactIds.hasError('required', 'contactIds')">This field is required</mat-error>
    </mat-chip-list>
</mat-form-field>

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

Unable to employ the inequality operator while querying a collection in AngularFire

I'm facing a challenge with pulling a collection from Firebase that is not linked to the user. While I've managed to query the user's collection successfully, I am struggling to retrieve the collection that does not belong to the user using ...

Angular2 - Leveraging data to dynamically control radio buttons

I am looking to implement radio buttons in a form using Angular 2 with a data-driven approach. In my component, I have set up a form as follows: import { Component } from '@angular/core'; import {FormControl, FormGroup, Validators} from '@a ...

Encountering a sign-in issue with credentials in next-auth. The credential authorization process is resulting in a

I am currently facing an issue with deploying my Next.js project on Vercel. While the login functionality works perfectly in a development environment, I encounter difficulties when trying to sign in with credentials in Production, receiving a 401 error st ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Angular is having trouble with the dropdown feature when using Semantic UI

I'm having trouble with the dropdown not displaying any items when I click on it. Here is the source code for reference: <div class = "ui centered grid"> <div class = "ten wide column"> <form class = "ui form"> <h4 cl ...

eslint warning: the use of '$localize' is flagged as an "Unsafe assignment of an `any` value"

When using $localize, eslint detects errors and returns two specific ones: Unsafe assignment of an 'any' value and Unsafe any typed template tag. It's quite strange that I seem to be the only one facing this issue while working on the proje ...

What is the method to transfer the outcome of a GET request into a POST request?

My task involves sending a GET request to retrieve information from . When the request is made, it generates a random image and returns a JSON object that includes details such as "fileSizeBytes" and "url". My goal is to extract the "url" value and then ...

Is it possible to load the surrounding markup in Angular before the guards are resolved upon the initial load of the router-outlet?

Within our Angular 12 application, we have implemented guards that conduct checks through API calls to the backend in order to validate the user's permissions for accessing the requested route. The default behavior of these guards follows an all-or-no ...

Error TS2694 is being caused by Electron Typescript Material-UI withStyles because the namespace "".../node_modules/csstype/index"" does not have an exported member called 'FontFace'

While I am experienced with Material-UI, I am relatively new to Electron and using React, TypeScript, and Material-UI together. Recently, I encountered an error while attempting to create an electron boilerplate code for future project initialization. Init ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Angular website showing only app.component.html on the frontend

I'm currently working on developing the frontend for my API and I've encountered an issue while trying to create a new component. Despite my best efforts, including setting up an app-routing.module.ts file, my application only displays the conten ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

ConfirmUsername is immutable | TypeScript paired with Jest and Enzyme

Currently, I am experimenting with Jest and Enzyme on my React-TS project to test a small utility function. While working on a JS file within the project, I encountered the following error: "validateUsername" is read-only. Here is the code for the utilit ...

Interacting with the Dropdown feature on the page causes the body of the page to shift

I am encountering an issue with 2 dropdowns in Datatables used to filter content. The problem arises when a dropdown is positioned on the right side of the page, causing a shift to the left by approximately 10px. Conversely, if the dropdown is placed on th ...

Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request. By enabling logging in TypeORM, I am able to observe the e ...

Adding a scss file to the library build using Angular CLI

I have been exploring different examples to develop reusable libraries. However, when I execute the command ng build library-name, the *.scss file is not present in the dist/library-name folder. How can I include style sheets in my build? Here are some h ...

Is it possible to write TypeScript and execute it directly with Node?

I am attempting to write some basic typescripts but I am encountering an issue with the setup below: node src/getExchangeAndTickerList.ts import * as mkdirp from 'mkdirp'; ^^^^^^ SyntaxError: Cannot use import statement outside a module ...

unexpected behavior with the mat-checkbox control

Using mat-checkbox within an Angular application has brought up a global issue for me. I have a formGroup with a mat-checkbox and a text input field. Upon clicking the mat-checkbox, a new FormGroup is instantiated with the same fields as before, along with ...

Discover how to access JSON data using a string key in Angular 2

Trying to loop through JSON data in angular2 can be straightforward when the data is structured like this: {fileName: "XYZ"} You can simply use let data of datas to iterate over it. But things get tricky when your JSON data keys are in string format, li ...

Trouble viewing information on initial try

I am currently facing an issue with retrieving data from firestore. Initially, everything was working perfectly fine. However, I now need to incorporate a check to verify if the user is logged in. If the user is not logged in, they should be redirected to ...