gpt4 book ai didi

angular2-forms - Angular2 Material2 - 如何在表单重建时禁用/启用 mat-datepicker-toggle

转载 作者:行者123 更新时间:2023-12-02 03:31:22 25 4
gpt4 key购买 nike

Angular 版本 5.2.4,Material2 5.2.4

我正在使用以下元素组合:

  • mat-formfield
  • 使用 matinput 指令进行输入
  • mat-datepicker
  • mat-datepicker-toggle

...采用数据源更改时重建的形式。

我可以在初始表单构建中将输入和 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 的禁用输入绑定(bind)到表单控件的禁用属性:

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

关于angular2-forms - Angular2 Material2 - 如何在表单重建时禁用/启用 mat-datepicker-toggle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51738051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com