I create a custom text-input
component based on Angular Material Form Field
<div class="{{classes}}">
<mat-form-field appearance="outline">
<mat-label>{{label}}</mat-label>
<input matInput
#input="ngModel"
[type]="type"
[attr.maxlength]="maxlength"
[attr.minlength]="minlength"
[placeholder]="placeholder || ''"
[(ngModel)]="value"
[required]="required"
[readonly]="readonly">
<mat-hint align="end" *ngIf="counter" class="text-sm text-muted">{{input.value.length}}{{maxlength ? '/'+maxlength : ''}}</mat-hint>
<span matTextPrefix *ngIf="textPrefix">{{textPrefix}}</span>
<span matTextSuffix *ngIf="textSuffix">{{textSuffix}}</span>
<mat-hint *ngIf="hint" class="text-sm text-muted">{{hint}}</mat-hint>
<mat-error *ngIf="input.invalid && (input.dirty || input.touched)" class="text-sm">
<!-- Some error messages here -->
</mat-form-field>
</div>
import { Component, Input, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { AbstractValueAccessor, MakeProvider } from "../form.accessor";
@Component({
selector: 'text-input',
templateUrl: './text-input.component.html',
styleUrls: ['../form-field.component.css'],
providers: [MakeProvider(TextInputComponent)]
})
export class TextInputComponent extends AbstractValueAccessor {
@ViewChild('input', {static: false}) input: NgForm
@Input() label:string="";
/* other inputs here */
}
AbstractValueAccessor is inspired from this anwer
When I tried using it in a form It is not detected in form control
<form #formCtrl="ngForm">
<text-input [(ngModel)]="entity.name" #name="ngModel"
label="Name" [required]="true">
</text-input>
<!-- Other similar fields -->
<button (click)="submit()">Send</button>
</form>
submit only contains console.log(formCtrl)
for debugging and its showing empty controls
NOTE: I can't switch to
reactive forms
and use formControlName attribute