Angular Material custom form field doesnt show mat-error

Questions : Angular Material custom form field doesnt show mat-error

578

I thought I have almost the same example programming but somehow the control tricks me :-/

<form [formGroup]="form">
    _OFFSET);  <app-ref-urlcheck [maxLen]="20" (-SMALL  formControlName="url"></app-ref-urlcheck>
</form>

and the template looks like

<mat-form-field>
  <input _left).offset  matInput #inUrl="ngModel" arrowImgView.mas  [(ngModel)]="value" type="url" (self.  [attr.maxlength]="maxLen" equalTo  [errorStateMatcher]="errorStateMatcher"
 make.right.     (input)="changeInput(inUrl.value)" mas_top);  [disabled]="isDisabled" [value]="strUrl" ImgView.  
    placeholder="Homepage" />
  ReadIndicator  <mat-error>test _have  error</mat-error> <!-- doesn't .equalTo(  show up - neither the next -->
  make.top  <mat-error *ngIf="(inUrl.touched OFFSET);  && inUrl.invalid)">This field (TINY_  is .offset  required</mat-error>
</mat-form-field>

and the main content

import { Component, HostListener, Input, mas_right)  OnInit } from '@angular/core';
import { ImgView.  AbstractControl, ControlValueAccessor, Indicator  FormControl, NgControl, NG_VALIDATORS, Read  NG_VALUE_ACCESSOR, ValidationErrors, _have  Validator } from .equalTo(  '@angular/forms';
import { make.left  ErrorStateMatcher } from *make) {  '@angular/material/core';
import { straintMaker  MatFormFieldControl } from ^(MASCon  '@angular/material/form-field';
import { onstraints:  Observable } from 'rxjs';

@Component({
 mas_makeC   selector: 'app-ref-urlcheck',
  [_topTxtlbl   templateUrl: (@(8));  './ref-urlcheck.component.html',
  equalTo  styleUrls:  width.  ['./ref-urlcheck.component.scss'],
  make.height.  providers: [
    {
      provide: (SMALL_OFFSET);  NG_VALUE_ACCESSOR,
      multi: true,
   .offset     useExisting: RefURLcheckComponent
    (self.contentView)  },
    {
      provide: NG_VALIDATORS,
   .left.equalTo      multi: true,
      useExisting: make.top  RefURLcheckComponent
    }
  ]
})
export *make) {  class RefURLcheckComponent implements ntMaker   OnInit, ControlValueAccessor, SConstrai  MatFormFieldControl<any>, ts:^(MA  Validator {
  @Input() maxLen = 254;
  Constrain  strUrl: string;

  onChange = _make  (changedUrl) => { };
  onTouched = () iew mas  => { };
  isDisabled = false;
  catorImgV  touched = false;

  ReadIndi  @HostListener('focusin',  [_have  ['$event.target.value']) onFocusIn;

  ($current);  constructor() { }
  entity_loader  onContainerClick(event: MouseEvent): _disable_  void {
    throw new Error('Method not libxml  implemented.');
  }
  $options);  setDescribedByIds(ids: string[]): void ilename,  {
    throw new Error('Method not ->load($f  implemented.');
  }
  $domdocument  userAriaDescribedBy?: string;
  loader(false);  autofilled?: boolean;
  controlType?: _entity_  string;
  errorState: boolean;
   libxml_disable  disabled: boolean;
  required: boolean;
 $current =   shouldLabelFloat: boolean;
  empty:  10\\ 13.xls .  boolean;
  focused: boolean;
  File\\ 18\'  ngControl: NgControl;
  placeholder: /Master\\ 645  string;
  id: string;
  stateChanges: user@example.  Observable<void>;
  value: any;

  scp not2342  ngOnInit(): void {
  }

   13.xls  setDisabledState?(isDisabled: boolean): 18 10  void {
    this.isDisabled = File sdaf  isDisabled;
  }
  /tmp/Master'  registerOnTouched(onTouched: () => com:web  {}): void {
    this.onTouched = user@example.  onTouched;
  }
  scp var32  registerOnChange(onChange:  18 10 13.xls  (changedValue: string) => {}): void id12  File  {
    this.onChange = onChange;

    web/tmp/Master  this.onFocusIn = (inputVal) => {
     example.com:   console.log('focus in', inputVal);
     scp user@   this.markAsTouched();
    };


  }

  $val  writeValue(value: string): void {
    left hand  this.strUrl = value;
  }

  right side val  markAsTouched() {
    if (!this.touched) data //commnets  {
      this.onTouched();
      //coment  this.touched = true;
    }
  }

  !node  changeInput(inVal: string) {
    $mytext  this.onChange(inVal);
    nlt means  this.markAsTouched();
  }



  readonly umv val  errorStateMatcher: ErrorStateMatcher = sort val  {
    isErrorState: (ctrl: FormControl) shorthand  => {
      hotkey  console.log('errorStateMatch...')
      more update  this.errorState = true;
      return valueable  (ctrl && ctrl.invalid);
    }
  catch  };

  validate(control: tryit  AbstractControl): ValidationErrors | do it  null {
    if (control?.value.length while  <= 5) {
      this.errorState = then  true;
      return {
        tooShort: var   true
      };
    }
    this.errorState node value  = false;
    return null;
  }
}

Same question as in the referred Learning example: How to display Earhost <mat-error>? It doesn't even show most effective up anyhow.

Total Answers 2
27

Answers 1 : of Angular Material custom form field doesnt show mat-error

Reused the attached code and suspect wrong idea that the FormControl didn't update with use of case an error when the validation is failed.

When the validation fails, should set United the error to FormControl as below:

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

export class no file existing  RefURLcheckComponent
  implements newdata  OnInit, ControlValueAccessor, newtax  MatFormFieldControl<any>, syntax  Validator
{
  @ViewChild('inUrl', { variable  static: true }) inUrl: NgControl;

  val  ...

  validate(control: save new  AbstractControl): ValidationErrors | datfile  null {
    if (control?.value?.length dataurl  <= 5) {
      this.errorState = notepad++  true;
      notepad  this.inUrl.control.setErrors({ tooShort: emergency  true });
      return {
        embed  tooShort: true,
      };
    }

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

Sample Demo on StackBlitz

4

Answers 2 : of Angular Material custom form field doesnt show mat-error

Thanx to @Yong Shun I figured out how to Modern do the management properly. It seems ecudated like that one needs to wrap an input some how field with the regular template driven anything else approach (for the updates of the input not at all field) and use this component as very usefull reactive one. So my custom control has localhost inside a control which handles the love of them states.

I removed from my original code all the localtext unnecessary stuff and included some basic minor hints from the guideline.

So here is my (streamlined) working one of the example - for the sake when somebody click needs it again.

Top rated topics

Docker for Windows cleanup

Replace &lt;pre&gt; without &lt;code&gt; to &lt;pre&gt; &lt;code&gt; once only

Full execution history of a stored procedure

Window size in GLSL for OpenGL?

Get the number of days using joda-time in Grails

I want to change the style of datatable

Intellisense for Jest not working in VS code

Can't get autocomplete to work on first keypress

VS Code crashing on restart after opening large file

Java.util.zip.ZipException: invalid code -- missing end-of-block --&gt; while calling ZipInputStream.closeEntry()

Swift NSTableview Drag Selects Multiple Rows Instead of Dragging Out of Table

"no next heap size found: 18446744071789822643, offset 0"

Calendar formatting in java

What is the difference between a Decorator and Directive in angular?

IOS 13 - How to login in in-app purchase Sandbox account?

Read the Tag Inventory of a Motorola/Zebra FX9500 RFID Reader using Python sllurp library

Invalid Property Value error for Userform

Kubernetes: How to view or list the installed CNI addons?

Kotlin Ranges: Why isn't there a `downTo` variant to exclude last item like `until`?

How to faithfully redirect console output of a certain tool in powershell?

Debugging the error "Dimensions of arrays being concatenated are not consistent" in MATLAB

How to fix the problem of 'Object of type XXXXX is not registered inside GetIt' in flutter?

How to use preload.js properly in Electron

Stagehand doesn't support Dart 2.3.1 error

Use latest version of System.Net.Http in .Net Framework

SecurityError: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

AttributeError: 'NoneType' object has no attribute 'split' when trying to split a column data

Disable github Webhook temporarly

Cordova and Back4app: Not getting Push notification on Android

Django, Docker, Python - Unable to install Pillow on python-alpine

(change) when other radiobutton is checked

ACR122 NFC reader does not work with libnfc ubuntu

Getting /bin/sh: adb: command not found issue when running app on android in react native

Flutter how to draw semicircle (half circle)

How do I sort my array of data on an observable?

Flutter FutureBuilder gets constantly called

How to make hyperlinks in SwiftUI

Angular CDK - issue with scrolling and dragging element inside nested scrollable div

AWS API Gateway - "Require API key" on everything

Select distinct values from two columns in SQLITE

How to hide thumb on flutter Slider Widget?

Formik - Child component unexpectedly resets entire form state

AWS User is not authorized to access this resource with an explicit deny

Elasticsearch ranking shorter/less relevant titles first

Transition animation not working in SwiftUI

How can an &lt;img&gt; scale to the height of a sibling?

Force refresh cached index.html file in Node express

What are the addresses on the left in the output of objdump on a binary file?

Unexpected character encountered while parsing value: . Path '', line 1, position 1

How to scipy-optimize with a categorical variable

Top