In a reactive Angular form, I want to disable the input so the user only uses the calendar. I use this : HTML
<mat-form-field>
<mat-label for="date">Starting date : </mat-label>
<input matInput [matDatepicker]="date" [min]="startDate" placeholder="mm/dd/yyyy" formControlName="date" disabled>
<mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
<mat-datepicker #date disabled="false"></mat-datepicker> <mat-error *ngIf="form.controls['date'].invalid">{{getErrorMessage('date')}}</mat-error>
</mat-form-field>
The submit button
<button type="submit" [disabled]="form.invalid">Create project</button>
TS
ngOnInit() {
this.form = new FormGroup({
date: new FormControl({ disabled: true, value: '' }, [Validators.required])
})
}
It works (the input is disabled and the calendar works) but the problem is with my submit button. If another required field is empty the submit botton is disabled. But if the datepicker isn't used to select a date (and other required fields have an input) the submit button is not disabled.
I also have a warning message in the browser console : >
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
you. We recommend using this approach to avoid 'changed after checked' errors.
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
>
<input matInput [matDatepicker]="date" [min]="startDate" placeholder="mm/dd/yyyy" formControlName="date" /*disabled*/>
– Leandroform = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.required), last: new FormControl('Drew', Validators.required) });
– Leandro