Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl.

<mat-form-field [formGroup]="myForm">
  <input matInput formControlName="myFormName" autocomplete="off" 
         (ngModelChange)="dataChanged(myValue)" [ngModel]="myValue">
  <mat-error>
    Error! Value must be between <strong>{{minVal}}</strong>
    and <strong>{{maxVal}}</strong>.
  </mat-error>
</mat-form-field>

However, I am facing an issue where ngModelChange is triggered multiple times during initialization when the ngModel value myValue is set from HTTP calls in a service. It seems like there may be a conflict between template-driven and reactive forms.

My goal is to bind data two ways to the input while also displaying mat-errors without unnecessary ngModelChange events triggered when the input is populated with data on initialization.

Answer №1

The form structure in your Angular project might resemble the following layout:

import { Component } from "@angular/core";
import {
  FormGroup,
  FormControl,
  Validators
} from "@angular/forms";

/** @title Custom ErrorStateMatcher Input */
@Component({
  selector: "input-error-state-matcher-example",
  templateUrl: "./input-error-state-matcher-example.html",
  styleUrls: ["./input-error-state-matcher-example.css"]
})
export class InputErrorStateMatcherExample {
  minVal = 10;
  maxVal = 25;

  myForm = new FormGroup({
    myFormName: new FormControl("", [
      Validators.minLength(this.minVal),
      Validators.maxLength(this.maxVal)
    ])
  });
}

In this code snippet, the minLength and maxLength validators have been set up.

Furthermore, the binding between the form and template is established using [formGroup] and formControlName directives.

Angular will handle all validations for you seamlessly.

To retrieve errors, simply access the errors property on myForm.controls['myFormName'] like so:

<mat-form-field [formGroup]="myForm">
    <input matInput formControlName="myFormName" autocomplete="off">
    <mat-error *ngIf="myForm.controls['myFormName'].errors">
        Error! Value must be between <strong>{{minVal}}</strong>
        and <strong>{{maxVal}}</strong>.
    </mat-error>
</mat-form-field>

For reference, check out this Live 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

Providing access to information even in the absence of JavaScript functionality

Is it possible to make the content of a webpage using jQuery/JavaScript visible even when JavaScript is disabled? Currently, I have a setup where clicking on an h2 header will display information from div tags using the jQuery function. I've made sur ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...

Error: The nested property of the dynamic type cannot be indexed

Within my coding project, I've devised an interface that includes various dynamic keys for API routes, along with the corresponding method and response structure. interface ApiRoutes { "auth/login": { POST: { response: { ...

Is there a way to insert a record upon the user clicking on the Add Record button?

// Here is my Component code // I want to figure out how to add a new row to the table with fresh values. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-uom', templateUrl: './uom.component.html ...

What can be done to stop Bootstrap columns from shifting positions or stacking on top of each other unexpectedly?

I'm currently working on a testimonial section for my project. The challenge I'm facing is that the content within the 4 divs is not evenly distributed. As a result, when I try to adjust the width of the screen and expect them to align in a 2-2 f ...

What is the best way to implement individual error handling for each function within combineLatest?

I'm looking for guidance on how to handle errors in each function within this `combineLatest` operation. Check out the code snippet below: const combined = combineLatest( this.myservice1.fn1(param), this.myservice2.fn2(), this.myservice3.fn3() ...

What is the process for redirecting an API response to Next.js 13?

Previously, I successfully piped the response of another API call to a Next.js API response like this: export default async function (req, res) { // prevent same site/ obfuscate original API // some logic here fetch(req.body.url).then(r => ...

Animate the downward movement of the parent of a specific element, while simultaneously animating the upward motion of all others that are

When clicking a button, I am trying to slide down only the ul elements that are parents of the li.newlist element, while sliding up all the others. Although I have successfully managed to slide down the desired elements, I am unsure how to define the secon ...

How can you assign a div ID to an image with a backlink included?

I need assistance in centering an image with a back link inside a div id, positioned 850px to the left. Additionally, I require another Div Id containing text centered on the same line within that same 850px space. Below is my CSS: #container3 > div { ...

What is the best way to resize an image in HTML based on a percentage of its height?

Within my HTML code, I have a PNG image that has been adjusted in size using CSS: .adjust-image { border:1px solid #021a40; display: block; width: auto; max-width: 100%; max-height: 1000px; } .img-container { position: relative; } ...

JavaScript - Removing Content from an Element

I have a coding script that adds an image preview of uploaded images. The issue I am facing is that the previous image does not clear when the form is filled out again. The id of the div where thumbnail images are being displayed is "thumbnail". Can someo ...

Choose everything except for the information determined by the search

Currently facing an issue with the select all functionality. I found a code snippet on this link but it's not exactly what I need. I want to modify the select all feature so that it is based on the search value. For instance, if I have a set of data ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Guide to positioning an image absolutely within a div

I am struggling to position a small close image within a div without success. The goal is for the image to always appear on the left side of the div, regardless of the content. The content consists of a text label with a maximum length of 8 characters. Iss ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

Issues with typescript compiler when using React-beautiful-dnd

I recently updated react and react-beautiful-dnd to the newest versions and now I am encountering many type errors in my code: {sortedDimensions.map((dimension: any, index: number) => ( <Draggable key={index} ...

Implementing a configuration file into a client-side web application using asynchronous methods

Currently, I am facing a challenge with an SPA that is being developed using various custom components from different sources. The main issue at hand is how to initialize certain settings (such as Endpoint URLs) using a settings file that can be configure ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Looking to establish combinations in typescript? The answer lies in utilizing a discriminated union

I've been working with Typescript and I'm curious if it's possible to specify the valid combinations of input for a function. Below is a simplified version of the code: interface ActionType { type: string, payload: { count?: ...