【问题标题】:One view for edit and add page with reactive Form使用反应式表单编辑和添加页面的一种视图
【发布时间】:2020-09-22 18:13:54
【问题描述】:

我想使用一个角度组件来编辑和显示客户的详细信息(用作示例)。

通常我会实现一个反应式表单(大约 15 个控件)并禁用所有控件,这些控件不应像此处所示那样可编辑:

form = this.formBuilder.group({
  name: [""],
  birthday: [{value:"", disabled: true}],
...
)};

问题是:如果我想使用带有表单的视图来显示客户的详细信息,输入字段也会出现禁用的外观/样式。

为了防止这种情况,我正在考虑从 FromControls 中删除 disabled 标记,并在组件的 HTML 中实现以下逻辑:

<input matInput formControlName="birthday" readonly [ngClass]="{'disabled-look': this.isEditMode === true}">

// css
.disabled-look{
color: gray;
}

现在输入字段总是只读的。 如果视图处于 editMode 中,则输入字段会获得一种使 ist 看起来不可编辑的样式。 如果视图未处于编辑模式,则输入字段是只读的,但不会显示为禁用状态,这是我想要实现的。

使用这种方法有什么问题吗?有更聪明的方法吗?

提前致谢! :D

编辑:

基于@Gonzalo 的 isEditMode 的另一种方法是
&lt;input *ngIf="this.isEditMode" matInput formControlName="birthday"&gt;
&lt;input *ngIf="!this.isEditMode" matInput value="{{this.customer.birthday | date}}"&gt;

并将禁用的标签再次添加回 FormControl

【问题讨论】:

    标签: angular typescript angular-reactive-forms


    【解决方案1】:

    尝试使用:

    <input type="text" [readonly]="!isEditMode" [disabled]="isEditMode">
    

    【讨论】:

      【解决方案2】:

      您可以根据isEditMode 使用不同的输入。

      <input *ngIf="this.isEditMode" matInput formControlName="birthday" disabled>
      <input *ngIf="!this.isEditMode" matInput formControlName="birthday" readonly>
      

      【讨论】:

      • 谢谢你的回答,我也想到了这个。但是在表单的 html 中使用 disabled 会导致以下警告:looks like you're using the disabled attribute with a reactive form directive [..] 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) });
      猜你喜欢
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2014-02-05
      • 2021-04-02
      • 2017-08-30
      • 2016-09-12
      相关资源
      最近更新 更多