I have some data bindings in my app, which bind to a provider, but now I'd like to add some form validation. The problem is I get an error when I start trying to use [(ngModel)]
with the form validation.
The error message I get indicates:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive \"formControlName\" instead. Example:
<div [formGroup]=\"myGroup\"> <input formControlName=\"firstName\"> </div> In your class: this.myGroup = new FormGroup({ firstName: new FormControl() }); Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions: Example: <div [formGroup]=\"myGroup\"> <input formControlName=\"firstName\"> <input [(ngModel)]=\"showMoreControls\" [ngModelOptions]=\"{standalone: true}\"> </div>
If I make it standalone ( [ngModelOptions]=\"{standalone: true}
) then I start getting errors ( Template parse errors: Can't bind to 'ngModelOptions' since it isn't a known property of 'ion-input'.
), but outside of that it seems that the form validation probably wouldn't work either. On the other hand if if I remove the ngModel then the data is no longer bound to my provider.
Here is a very abreviated version of my code:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CaseProvider } from '../../providers/caseProvider';
@Component({
selector: 'page-form',
template: `
<ion-header>
</ion-header>
<ion-content>
<div [formGroup]="myFormGroup">
<ion-item>
<ion-label>Record number</ion-label>
<ion-input formControlName="record" [(ngModel)]="caseProvider.record"></ion-input>
</ion-item>
<button ion-button block (click)="saveCase()">
<span>Save</span>
</button>
</div>
</ion-content>
`
})
export class MyPage {
myFormGroup: FormGroup;
constructor(public formBuilder: FormBuilder, public caseProvider:CaseProvider) {
this.myFormGroup = formBuilder.group({
record: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('.*[0-9].*')])]
});
}
saveCase(){
//save code here
}
}
How do I get databinding to a provider (which has getters and setters in it), and do validation with a formGroup at the same time?
Thanks!