0

I have a custom control that implements both MatFormFieldControl and ControlValueAccessor, and although the form is invalid and has error I cannot get mat-error to display.

Main formgroup:

<form [formGroup]="formGroup">
  <mat-form-field>
    <app-test-input formControlName="testControl"></app-test-input>
    <mat-hint>test</mat-hint>
    <mat-error *ngIf="formGroup.get('testControl').hasError('required')">
      required
    </mat-error>
  </mat-form-field>
  <button (click)="submit()">Submit</button>
</form>
<p *ngIf="formGroup">
  {{formGroup.value | json}} {{
  formGroup.get('testControl').hasError('required') }}
</p>

custom control:

<div [formGroup]="FormGrp">
  <input formControlName="data" (input)="input()" />
</div>

Here is a stackblitz https://stackblitz.com/edit/angular-tzgaxz-upn2yn

I would expect clicking the submit button to show the error, but I cannot figure out where I am going wrong. The error only appears when blurring the input.

1 Answer 1

0

Ok, for start in your stackblitz you're not importing MatFormFieldModule which is required for mat-error to work properly (not rly, but I will keep it simple). Next problem is that mat-form-field is looking for direct input descendant with matInput directive. I am assuming you're trying to customize input visuals to your liking. I don't think using material design that way is correct approach. Just create your own component with similar approach to error handling as Angular Material.

I've provided corrected version to your stackblitz as suggested in Angular Material documentation. As you see it's working properly. https://stackblitz.com/edit/angular-tzgaxz-kmbtka?file=app/form-field-overview-example.html

In theory you can fight with that behavior, however I do not advice for that.

PS. Your problem is not related to the "error" state of ReactiveFormInput, but to mat-form-field controling visibility of mat-error element from within it's own styles/component.

Sign up to request clarification or add additional context in comments.

3 Comments

I need to keep the component though, you removed it and replaced it with input directly.
@Paul Yes, I had to do that. I don't know why you need to keep component, but if you do, I suggest creating your own wrapper instead of using material one. As I said in my response mat-form-field requires "matInput" as a direct child, because it needs to hook into MatFormFieldControl to check for input events like "focus". A lot of things from mat-form-field depends on direct input child with matInput directive. Just get rid of material and create your own error component and input-wrapper :) No need to fight with library.
Sorry, but I am looking to making it work with a custom control per my example. Thank you for looking at it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.