Disable (make read-only) text input on mat-datepicker when using a reactive form
To create a disabled FormControl
is really simple.
1 - Don't use disabled attribute in your template;
2 - Instantiate your FormGroup
like this:
this.formGroup = this.formBuilder.group({
dateJoined: { disabled: true, value: '' }
// ...
});
That being said, although you want to prevent users from typing something in the input, you still want to let them select a date by clicking the button (more specifically in matSuffix
), right?
If it's correct, disable
doesn't work for this case, because it'll disable all the input (including the button in matSuffix
).
To solve your case, you can use readonly
. Instantiate the FormGroup
normally and then in template:
<input
matInput
readonly <- HERE
[matDatepicker]="dateJoined"
placeholder="Date joined"
formControlName="dateJoined">
DEMO
To expand on developer033's answer, to dynamically toggle the readonly
state of the input
, modify the readonly
property using a component variable.
Dynamically Toggle Readonly
See Stackblitz Demo
app.component.html
<input matInput
[readonly]="inputReadonly" <!-- Update `readonly` property using variable -->
[matDatepicker]="dateJoined"
placeholder="Date joined"
formControlName="dateJoined">
app.component.ts
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {VERSION} from '@angular/material';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html'
})
export class AppComponent {
formGroup: FormGroup;
inputReadonly = true;
version = VERSION;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({
dateJoined: ''
});
}
public toggleInputReadonly() {
this.inputReadonly = !this.inputReadonly;
}
}