Reputation: 5522
I have a validator of the type required and maxLength in my input field and I'm trying to have the cleanest code on my HTML. I tried to do the following but won't work
HTML
(this won't work)
<form [formGroup]="creditCardForm">
<input type="text" pInputText formControlName="cardHolderName" required maxlength #cardHolderName/>
<label *ngIf="form.cardHolderName.invalid &&
(form.cardHolderName.dirty || form.cardHolderName.touched)" class="invalidField">Cardholder name is required</label>
</form>
TS
form = this.buildCreditCardForm(this.fb).controls;
.
.
buildCreditCardForm(fb: FormBuilder): FormGroup {
return fb.group({
cardHolderName: ['', [Validators.required, Validators.maxLength(50)]],
.
.
}
HTML (This works but it's too long, to dirty)
<form [formGroup]="creditCardForm">
<input type="text" pInputText formControlName="cardHolderName" required maxlength #cardHolderName/>
<label *ngIf="fcreditCardForm.controls.cardHolderName.invalid &&
(creditCardForm.controls.cardHolderName.dirty || creditCardForm.controls.cardHolderName.touched)" class="invalidField">Cardholder
name is required</label>
</form>
Upvotes: 2
Views: 2112
Reputation: 8121
you are mixing both reactive validators and template validators. not sure why you are complicating things, reactive forms are simple.
bulit you a Demo with your form:
HTML:
<form [formGroup]="creditCardForm">
<input type="text" formControlName="cardHolderName"/>
<label *ngIf="creditCardForm.get('cardHolderName').invalid">Cardholder name is required</label>
</form>
Component:
creditCardForm;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.creditCardForm = new FormGroup({
'cardHolderName': new FormControl(null, [Validators.required, Validators.maxLength(5)])
});
}
Take it away enhance and adjust to your needs.
Upvotes: 2