[Fixed] How to display a mat-error message without a form control, but with matInput?

Issue

I have this code in my Material table:

<ng-container matColumnDef="columnDef">
   <th mat-header-cell *matHeaderCellDef>Column heading</th>
   <td mat-cell *matCellDef="let row">
       <mat-form-field>
             <input matInput [(ngModel)]="row.myField">
             <mat-error *ngIf="row.myField > 0"> My error message </mat-error>
        </mat-form-field>
   </td>
</ng-container>

The thing is that mat-form-field is not a FormControl, but it would be nice if mat-error would somehow validate this input and display the error message.

Can someone tell me if it is possible?

Solution

you can use a span attribute with custom style:

<mat-form-field>
      <input matInput [(ngModel)]="row.myField">
      <span class="error" *ngIf="row.myField > 0"> My error message </span>
</mat-form-field>

component.css (this is just an example)

.error {
  font-size: 10px;
  color: red;
}

Leave a Reply

(*) Required, Your email will not be published