I have a reactive form. The setup is similar to this:
myForm: FormGroup;
this.myForm= new FormGroup({
name: new FormControl("", [Validators.required, Validators.maxLength(15), Validators.pattern('...')]),
...
});
I use this on my form like this:
<input
type="text"
formControlName="name"
/>
<div *ngIf="name.errors?.required">
Name is required
</div>
<div *ngIf="name.errors?.maxlength">
Name must be {{ name.errors.maxlength.requiredLength }} characters
</div>
<div *ngIf="name.errors?.pattern">
Name has invalid characters.
</div>
This is just a cut down version of my form. I have multiple input and I've had to create the error div's for each input.
So to fix this I've tried to create a component. The component is very similar to the code above:
<input
type="text"
[formControlName]="formControlName"
/>
<div *ngIf="name.errors?.required">
Name is required
</div>
etc...
ts file:
@Component({
selector: 'app-text',
templateUrl: './text.component.html'
})
export class TextComponent {
@Input() formControlName: FormControl;
}
So on my form I'd like to use this component as follows:
<app-text [formControlName]="name"></app-text>
But I can't get this to work with the formControlName property.
Is this possible?
Thanks
I'm nearly there.
I've create this StackBlitz so show my progress:
Just struggling with the errors now and how to access the formControl to check for those errors