I recently encountered a situation where I needed to implement a reactive form in a component. It looked something like this...
form component.html
<form [formGroup]="form" class="do-form">
<div formGroupName="dot">
<div class="do-form__container">
<div class="do-form__group">
<label for="day">Day</label>
<input id="day" type="number" placeholder="XX" class="do-form__group__control" formControlName="day" />
</div>
<div class="do-form__group">
<label for="month">Month</label>
<input id="month" type="number" placeholder="XX" class="do-form__group__control" formControlName="month" />
</div>
<div class="do-form__group">
<label for="year">Year</label>
<input id="year" type="number" placeholder="XXXX" class="do-form__group__control" formControlName="year" />
</div>
</div>
<div class="do-form__errors" *ngIf="isValid()">
<p>Please enter a valid date</p>
</div>
</div>
</form>
In the corresponding form.component.ts file
form = this.fb.group({
dot: this.fb.group({
day: ['',
[
Validators.required,
Validators.min(1),
Validators.max(31)
]],
month: ['',
[
Validators.required,
Validators.min(1),
Validators.max(12)
]],
year: ['2018',
[
Validators.required,
Validators.min(1918),
Validators.max(2018)
]]
})
});
isValid() {
return (
!this.form.valid &&
this.form.get('dot.day').touched &&
this.form.get('dot.month').touched &&
this.form.get('dot.year').touched
);
}
Next, I needed to integrate this form within another page (app.component.html) like this
<app-form #formTool></app-form>
<button class="full-width-btn" (click)="next(); form.sendResult();">SEND</button>
In the app.component.ts file
import { formComponent } from '../form-component/form-component.ts'
export ...
@ViewChild(formComponent) form;
My main goal was to disable the send button until the form within the app form component was valid. However, I faced some challenges with this. I considered having a valid
event stored on a shared server, but I wasn't sure how to store this in a service. I also explored the option of using ngModel
for non-reactive forms, but I wasn't confident if that approach would work in this scenario.
If anyone has any insights or suggestions on how I can achieve this, I would greatly appreciate it!
UPDATE
I've attempted using [disabled]="form.invalid"
and [disabled]="!isValid()"
but the button remains clickable.
I also tried utilizing [disabled]=!form.isValid()
and [disabled]=!form.form.isValid()
Thank you for any assistance provided.