Angular2 Material2 - 如何 disable/enable mat-datepicker-toggle on form rebuild

Angular2 Material2 - How to disable/enable mat-datepicker-toggle on form rebuild

Angular 版本 5.2.4,Material2 5.2.4

我正在使用这种元素组合:

...在数据源更改时重建的表单中。

我能够在初始表单构建中将输入和 mat-datepicker-toggle 设置为禁用或启用。重建表单时,输入的禁用 属性 是可设置的。但是,对于初始表单构建后的任何表单重建,mat-datepicker-toggle 的禁用 属性 仍保持初始状态(无论是启用还是禁用)。

Material documentation 状态(我在此处的元素周围使用引号):

As with any standard "input element", it is possible to disable the datepicker input by adding the disabled property. By default, the "mat-datepicker" and "mat-datepicker-toggle" will inherit their disabled state from the "input element"

因此,在 重建表单后设置 mat-datepicker-toggle 的禁用/启用状态是我要解决的问题。

我已简化但有效的以下代码,以展示我最近尝试过的内容。如果您需要更多信息,请告诉我。

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { MatDatepickerModule, MatIconModule,
  MatInputModule, MatNativeDateModule,} from '@angular/material';

@NgModule({
  exports: [ MatDatepickerModule, MatIconModule,
    MatInputModule, MatNativeDateModule ]
})
export class MaterialModule { }

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule, 
MaterialModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { VERSION } from '@angular/material';

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  formGroup: FormGroup;
  version = VERSION;
  disableMe = false;
  infamousDate = "2018-08-22T12:34:56.789Z";

  constructor() { }

  ngOnInit() {
    this.rebuildForm();
  }
  rebuildForm() {
    this.disableMe = !this.disableMe;
    this.formGroup = new FormGroup({
      dateJoined: new FormControl(
        { disabled: this.disableMe, value: this.infamousDate })
    });
  }
}

app.component.html

<form class="basic-container" [formGroup]="formGroup">
  <mat-form-field>
    <input matInput [matDatepicker]="dateJoined" placeholder="Date joined" formControlName="dateJoined">
    <mat-datepicker #dateJoined></mat-datepicker>
    <mat-datepicker-toggle matSuffix [for]="dateJoined"></mat-datepicker-toggle>
  </mat-form-field>
</form>
<button (click)="rebuildForm()">click me</button><hr><span>date enabled: {{!disableMe}}</span>

这里是 Stackblitz.

中的相同代码

您需要将 mat-datepicker-toggle 的禁用输入绑定到表单控件的禁用 属性:

<mat-datepicker-toggle matSuffix [for]="dateJoined"
    [disabled]="formGroup.controls['dateJoined'].disabled">
</mat-datepicker-toggle>