My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended.

A custom component was created to manage errors, but it is not behaving correctly upon rendering.

Here is the relevant page code:

<mat-form-field appearance="outline">
  <input matInput placeholder="Enter your email" formControlName="ip" required>
  <app-form-field-error [form-control]="resourceForm.get('ip')"></app-form-field-error>
</mat-form-field>

This is the HTML for the custom component:

<mat-error >{{errorMessage}}</mat-error>

And here is the TypeScript code for the custom component:

import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-form-field-error',
  templateUrl: './form-field-error.component.html',
  styleUrls: ['./form-field-error.component.css']
})
export class FormFieldErrorComponent implements OnInit {

  @Input('form-control')
  formControl: FormControl;

  constructor() {}

  ngOnInit() {}

  public get errorMessage(): string | null {
    if (this.mustShowErrorMessage()) {
      return this.getErrorMessage();
    } else {
      return null;
    }
  }


  private mustShowErrorMessage(): boolean {
    return this.formControl.invalid && this.formControl.touched;
  }

  private getErrorMessage(): string | null {

    if (this.formControl.errors.email) {
      return 'Invalid email format';
    } else if (this.formControl.errors.minlength) {
      const requiredLength = this.formControl.errors.minlength.requiredLength;
      return `Must be at least ${requiredLength} characters long`;
    } else if (this.formControl.errors.maxlength) {
      const requiredLength = this.formControl.errors.maxlength.requiredLength;
      return `Must not exceed ${requiredLength} characters`;
    }
  }

}

Expected outcome: http://prntscr.com/o35s9k

Current result: http://prntscr.com/o35shk

Answer №1

After making some updates, the revised code now looks like this:

<mat-error >
    <app-form-field-error [form-control]="resourceForm.get('ip')"></app-form-field-error> </mat-error>

I also made a tweak to the app-form-field-error section:

<ng-container>{{errorMessage}}</ng-container>

Everything is running smoothly now!

Many thanks for your help!

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

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...

Embed the value of an array in HTML

Upon running console.log, the data output appears as follows: {TotalPendingResponseCount: 0, TotalRequestSendCount: 1, TotalRequestReceivedCount: 1, TotalRequestRejectCount: 3} To store this information, I am holding it in an array: userData : arrayResp ...

What is the best way to verify a field against a set of string values using Typescript in a NestJS application

I currently have an Enum containing various timezones listed below export enum Timezones { 'Europe/Andorra', 'Asia/Dubai', 'Asia/Kabul', 'America/Antigua' } In the DTO file, I am attempting to valid ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

Handling functions in Ant Design Select component with TypeScript types

I have a query. Antd offers a custom Select input with functions like onSelect, onChange, etc. I am utilizing the onSelect function which requires the following arguments: (JSX attribute) onSelect?: ((value: string | number | LabeledValue, option: OptionDa ...

What are the best methods for visually designing a database using Entity Framework Core?

I find myself contemplating the best approach to designing my database scheme for optimal efficiency and visual appeal. Currently, I am working on an ASP.NET Core application with Angular 2, utilizing Entity Framework Core ("Microsoft.EntityFrameworkCore" ...

What is the process for importing a JSON file into a TypeScript script?

Currently, I am utilizing TypeScript in combination with RequireJS. In general, the AMD modules are being generated flawlessly. However, I have encountered a roadblock when it comes to loading JSON or any other type of text through RequireJS. define(["jso ...

How to eliminate the button from Google Maps API using JavaScript

I am trying to implement a specific functionality on my map. When the user drags the map, I want a button named 'Search in this area' to appear. Once the user clicks on the button, it should disappear so that the search can't be performed ag ...

Tips for utilizing string interpolation in the style tag of an Angular component

@Component({ selector: 'app-style', template: ` <style> .test { color: {{ textColor }} } </style> ` }) export class StyleComponent { textColor = "red"; } The current method doesn't appear to b ...

What could be causing the error message to appear in Angular CLI when attempting to add a new component?

I recently started working on a new Angular app and I'm attempting to add a component for a login registration feature. This will be my first time building an app with Angular frontend and Bootstrap backend, as I am fairly new to development. Any advi ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Differences Between NgModule and AppComponent in Angular

Being a novice in the realm of Angular, I'm curious to know the distinction between CommonModule and BrowserModule, and when one should be prioritized over the other. ...

Mobile Devices and Local Storage: What You Need to Know for Safe and Efficient Use. Looking for advice from experienced developers

Need help with caching user input on an Angular11 + Firebase app? Let's discuss implementing a caching feature for a dynamic form section that can contain varying fields based on the use case. The goal is to save user input in LocalStorage to ensure ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

The primary filter for ag-Grid in Angular 2+

When using the default filtering on ag-grid, I find that the timing between typing and filtering is too quick. Is there a method to slow down this process? Perhaps instead of triggering the filter when typing stops, it could be activated by pressing a bu ...

Encountered an issue while trying to access a property that is undefined in the

How can I extract data from a dropdown menu and display it in a text box? For instance, if a user selects an ID from the dropdown, I want to show the corresponding name in the textbox. I hope this explanation is clear and properly conveyed, as my English s ...

What are the steps for personalizing themes in the Monaco editor?

I'm currently working on a code editor with Monaco. The syntax highlighting in Monaco for Javascript and Typescript only highlights keywords as dark blue, strings as brown, and numbers as light greenish-yellow. My goal is to customize the vs-dark the ...

Angular2 import functions properly on the Windows operating system, however, it encounters issues on the Linux

import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { User } from './../../class/User'; I am encountering the fol ...

Determine whether an element is visible following a state update using React Testing Library in a Next.js application

I'm looking to test a NextJS component of mine, specifically a searchbar that includes a div which should only display if the "search" state is not empty. const SearchBar = () => { const [search, setSearch] = useState(""); const handleSear ...

Visual Studio Code is encountering issues when trying to start a Node application

I am in the process of setting up a workflow for an express app using TypeScript, Visual Studio Code, and gulp. Here is the structure of my project: src/ <-- source files Start.ts Server.ts models/ Contact.ts Organization.ts bin/ <- ...