Reputation: 1894
I have a EditAssignment form which I need to populate with the existing values in the database and then validate the form. First I retrieved the form values from firebase like this.
this.assignment = this._db.object('/assignments-detail/' + asnDetailKey);
Then I stored the form values in a class variable (_assignment).
this.assignment.subscribe(asnDetails => {
this._assignment = asnDetails;
});
Then I populated the form using _assignment like this.
<form [formGroup]="form">
<div class="form-group">
<label for="subject">Assignment Subject</label>
<input type="text" class="form-control" id="subject" formControlName="subject" [value]="_assignment?.subject">
<div class="alert alert-danger" *ngIf="form.controls['subject'].touched && form.controls['subject'].hasError('required')">
Please enter assignment subject.
</div>
</div>
<div class="form-group">
<label for="dueDate">Due Date</label>
<input type="date" class="form-control" required="required" id="dueDate" formControlName="dueDate" [min]="today" [value]="_assignment?.dueDate">
<div class="alert alert-danger" *ngIf="form.controls['dueDate'].touched && form.controls['dueDate'].value==' | async'">
Please enter a valid due date.
</div>
</div>
<button type="button" class="btn btn-primary" (click)="onUpdate()" [disabled]="!form.valid">Edit Assignment</button>
</form>
And finally I validate in typescript file using validate() method which i call from ngOnInit.
validate() {
this.form = this._fb.group({
subject: ['', Validators.compose([Validators.required])],
dueDate: ['']
});
I am successfully able to retrieve the values from database and populate the form but it is not validating. For example, When i click on Subject textbox and then click out, it is showing error message please enter assignment subject
even though the textbox is not empty. Also the button is disabled.
Upvotes: 0
Views: 347
Reputation: 38171
It's not recommend for using templete-driven form
and model-driven form
at the same time.
For ReactiveForm, you should initialize elements by
this.form = this._fb.group({
subject: ['init value', Validators.compose([Validators.required])], // init here
...
});
and for your situation(change value of subject), you shouldn't use [value]
(which is for template-driven form), use patchValue
instead.
this.assignment.subscribe(asnDetails => {
this._assignment = asnDetails;
if (this._assignment.subject) {
this.form.get('subject').patchValue(this._assignment.subject);
}
});
Upvotes: 1
Reputation: 1
ngOnInit() {
this.form = this._fb.group({
subject:['', [Validators.required]],
dueDate: ['']
}
otherwise, u should trigger the function inside ngOnInit
ngOnInit() {
validate();
}
Upvotes: 0