The issue with displaying mat-error in a custom form field in Angular Material

I encountered a similar issue to the example mentioned, but the control seemed to deceive me :-/

<form [formGroup]="form">
    <app-ref-urlcheck [maxLen]="20" formControlName="url"></app-ref-urlcheck>
</form>

Here is how the template appears:

<mat-form-field>
  <input matInput #inUrl="ngModel" [(ngModel)]="value" type="url" [attr.maxlength]="maxLen" [errorStateMatcher]="errorStateMatcher"
    (input)="changeInput(inUrl.value)" [disabled]="isDisabled" [value]="strUrl" 
    placeholder="Homepage" />
  <mat-error>test error</mat-error> <!-- The following does not appear either -->
  <mat-error *ngIf="(inUrl.touched && inUrl.invalid)">This field is required</mat-error>
</mat-form-field>

Lastly, here is the main content of the code:

import { Component, HostListener, Input, OnInit } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormControl, NgControl, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { MatFormFieldControl } from '@angular/material/form-field';
import { Observable } from 'rxjs';

// Rest of the component remains unchanged ...

The question remains the same: How can I make the <mat-error> display correctly? It seems to be invisible in my case as well.

Answer №1

Utilized the provided code snippet and believe that the FormControl is not updating with an error message upon validation failure.

In case of a failed validation, the error should be assigned to the FormControl as shown below:

this.inUrl.control.setErrors({ tooShort: true });
import { ViewChild } from '@angular/core';

export class RefURLcheckComponent
  implements OnInit, ControlValueAccessor, MatFormFieldControl<any>, Validator
{
  @ViewChild('inUrl', { static: true }) inUrl: NgControl;

  ...

  validate(control: AbstractControl): ValidationErrors | null {
    if (control?.value?.length <= 5) {
      this.errorState = true;
      this.inUrl.control.setErrors({ tooShort: true });
      return {
        tooShort: true,
      };
    }

    this.errorState = false;
    this.inUrl.control.setErrors(null);
    return null;
  }
}

Check out a Sample Demo on StackBlitz

Answer №2

Thanks to the guidance of @Yong Shun, I have successfully optimized my management approach. It appears that wrapping an input field with the standard template-driven method is necessary for updating the input field, while using this component reactively. Thus, my custom control now contains a control that efficiently handles various states.

I have refined my original code by eliminating unnecessary components and incorporating some valuable insights from the recommendations.

For those who may require it in the future, here is the streamlined example of my working solution.

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

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

What is the best way to add an additional image to the first row in that vacant spot?

https://i.sstatic.net/7ODvY.pngI need to add an additional image in the top row, but there is currently empty space due to the left button (out now) potentially overlapping the image. This layout is using the bootstrap grid system with columns set to col-s ...

Versions of Angular that are compatible with Ionic 2 (do not have an exported member)

How do I determine the compatible Angular version for each Ionic version? I keep encountering errors like "has no exported member." For example: The module ".../node_modules/@angular/core/index" does not have an exported member called InjectionToken. The ...

Issues with Subject.subscribe occurring beyond the constructor

If you're looking for a straightforward service, I've got just the thing for you. import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class XmlService { items$: Subject<Item[]> = ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

What is the approach taken by this component to display its child elements?

While delving into the code of react-accessible-accordion, I found myself puzzled by the way it handles rendering its children. The snippet below is from Accordion.tsx: export default class Accordion extends React.Component<AccordionProps> { // ...

What is the best way to integrate Angular material into a Bazel-enabled project for a custom library development?

Is there a way to incorporate Angular material into a project enabled with Bazel in a custom library? Check out the code I am using: https://github.com/AkshayC1736/angular-bazel.git ...

What could be the reason for the custom component app-transition-group and app-transition-group-item not functioning properly in Angular 8, even though it was working fine

I developed a unique Angular8 custom component that rearranges list items. However, I keep encountering the following error: Can't bind to 'app-transition-group' since it isn't a known property of 'ul'. Do you have any sugge ...

display the picture depending on the circumstances

Is there a way for the image tag to display different images based on a condition? I attempted the code below, but it's not displaying the image: <img src="{{row.image}}!=null?'data:image/jpeg;base64,{{row.image}}':'./assets/img/qu ...

Remove a npm package from an angular application

When I run the following command on the command line and on gitBash: npm -g uninstall angualar2piwik --save I receive the following message: up to date in 0.16s The entry is not removed from package.json, nor are the node_modules removed. I have also ...

Exploring the capabilities of TypeScript in conjunction with the useRoute function on React Navigation version

When using useRoute, I am attempting to extract the parameters like this: const route = useRoute(); const { params } = route; const { id, name, } = params; Although everything is functioning correctly, the linter is pointing out that id and na ...

Encountering a Runtime Exception while utilizing MapQuest's direction routing feature on Ionic 3

I have successfully generated a map using the Ionic 3 framework, but I encountered a runtime error when attempting to use the L.mapquest.directions().route() function. Here are the imports: <link rel="stylesheet" href="https://unpkg.com/ ...

ANGULAR: Issue with filtering an array by clicking a button is not functioning

I've been attempting to apply a filter to my array by using modulo on the id when clicking multiple buttons. I initially tried using pipe but was advised to stick with .filter(). Despite watching numerous online tutorials, I keep encountering errors o ...

There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript. For example: // /pages/index.tsx import _ from 'lodash' export const MyComponent = () => { return ( <ul> { _.map(someArray, ...

Issue with Navigation menu dropdown not functioning properly on Angular version 12 with Bootstrap 5

I am attempting to integrate bootstrap with Angular through a CDN. Below is the content of my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Laboratorio Sigma< ...

`mat chip component in Angular Material is malfunctioning`

Whenever I input a string, it does not display properly within the designated textbox. HTML <mat-form-field class="favorite-fruits"> <mat-label>Favorite Fruits</mat-label> <mat-chip-list #chipList aria- ...

Issue: The error message "TypeError: React.createContext is not a function" occurs when using Next.js 13 alongside Formik with TypeScript

I'm currently working on creating a form using Formik in NextJs 13 (Typescript). However, the form I designed isn't functioning properly. To troubleshoot, I added code snippets from Formik's examples as shown below. Unfortunately, both my fo ...

Secure your NetSuite API calls with OAuth 1.0 signature authorization

After extensively reviewing the documentation and various posts on Stack Overflow about creating a signature for NetSuite OAuth1.0 with TBA, I believe that I have followed all of the necessary steps and correctly generated the key. However, upon making the ...

Learn how to configure settings in the config service by using Angular's APP_INITIALIZER feature

I am working on an Angular app where I need to implement runtime configuration in order to use the same build artifact for any target environment. The app should load settings from a backend .NET API, with the API URL specified in the config.json file loca ...

What's preventing me from utilizing $event to fetch an array of strings?

When attempting to transfer information from a child to a parent using event emitters and output, an error is encountered: Argument of type 'Event' is not assignable to parameter of type 'string[]'. Type 'Event' is missing t ...