To handle user input exceeding maxLength and dynamically add < mat-error > to the DOM in case of an error, I have implemented an attribute directive that enforces the character limit on input fields. This directive is used across multiple files in the project to ensure consistency. However, I now need a way to display a < mat-error > message when the limit is exceeded without manually adding it to each input field in every file. Is there a modular solution where this can be achieved using the existing directive?
<mat-form-field floatLabel="auto">
<input [formControl]="displayNameControl"
mongoIndexLimit
[charLength]="charLength"
matInput
name="displayName"
placeholder="Stack Name"
autocomplete="off"
required />
</mat-form-field>
Here's the directive implementation:
import { Directive, OnInit, NgModule, ElementRef, OnChanges, Input, SimpleChanges, Renderer2 } from '@angular/core';
@Directive({
selector: '[mongoIndexLimit]'
})
export class MongoIndexLimitDirective implements OnInit, OnChanges {
@Input() public charLength?: number;
private maxLength = 5;
constructor(
private el: ElementRef<HTMLElement>,
private renderer: Renderer2
) { }
public ngOnInit() {
this.el.nativeElement.setAttribute('maxLength', this.maxLength.toString());
}
public ngOnChanges(changes: SimpleChanges) {
if (changes.charLength.currentValue >= 5) {
const child = document.createElement('mat-error');
this.renderer.appendChild(this.el.nativeElement.parentElement.parentElement.parentElement, child);
}
}
}
Although I was able to append a < mat-error > element to the DOM through the directive, Angular does not recognize it as a compiled Angular Material component. It remains a non-functional placeholder.
I aim for the final output to include an input component with a set maxLength along with a dynamically generated mat-error that appears upon exceeding the limit similar to the example shown below:
https://material.angular.io/components/input/examples (titled Input with custom Error state matcher)
Excuse any language errors.