title: How to dynamically add a mat-error to a mat-input-field?
body: <p>I want to show an error when user exceeds maxLength by adding &lt; mat-error > dynamically to the DOM. </p>
  
  <p>I already have a <strong>attribute directive</strong> in place to limit the max length of an input field. I have it as a directive, since this gets applied to a lot of input fields across different files in the project. But now the problem is, I have to show a <strong>mat-error</strong> when the user exceeds the limit. I don't want to add &lt; mat-error > under every input fields across all files by myself , i want a <strong>modular</strong> solution. Can this be done by using the existing directive itself? </p>
  
  <pre><code>&lt;mat-form-field floatLabel="auto"&gt;
        &lt;input [formControl]="displayNameControl"
          mongoIndexLimit
          [charLength]="charLength"
          matInput
          name="displayName"
          placeholder="Stack Name"
          autocomplete="off"
          required /&gt;
      &lt;/mat-form-field&gt;
  </code></pre>
  
  <p>And this is my directive</p>
  
  <pre><code>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&lt;HTMLElement&gt;,
      private renderer: Renderer2
    ) { }
  
    public ngOnInit() {
      this.el.nativeElement.setAttribute('maxLength', this.maxLength.toString());
    }
  
    public ngOnChanges(changes: SimpleChanges) {
      if (changes.charLength.currentValue &gt;= 5) {
        const child = document.createElement('mat-error');
        this.renderer.appendChild(this.el.nativeElement.parentElement.parentElement.parentElement, child);
      }
    }
  
  }
  </code></pre>
  
  <p>When i try the above i was able to append a &lt; mat-error > element to the DOM, but angular doesn't treat it as a compiler &lt; mat-error > angular material. it is just a dummy &lt; mat-error > and not a material component.</p>
  
  <p>I desire the result to be an input component with maxLength set and a dynamically generated mat-error which shows when the limit exceeds, just like how it is in the example below.</p>
  
  <p><a href="https://material.angular.io/components/input/examples" rel="noreferrer">https://material.angular.io/components/input/examples</a> 
  (titled Input with custom Error state matcher)</p>
  
  <p>Sorry for my bad English .</p>