You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击Save按钮后将Angular表单设置为不可编辑状态

解决方案

方法1:通过Angular表单API禁用整个表单

利用Angular表单的disable()方法,在点击保存按钮后直接禁用整个表单,所有控件会自动变为不可编辑状态,同时浏览器会默认添加禁用样式。

修改后的模板代码

<form [formGroup]="calculateForm">
  <div class="form-group row">
    <p for="inputFrom" class="col-sm-4">Distance traveled(km):</p>
    <div class="col-sm-4">
      <input type="text" numbersOnly class="form-control form-control-md"
             formControlName="distance">
    </div>
  </div>

  <button type="button" (click)="calculate()" class="btn btn-success"
          [disabled]="calculateForm.disabled">
    {{ 'Save' | translate }}
  </button>
  <br>
</form>

组件TS代码

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  calculateForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.calculateForm = this.fb.group({
      distance: ['']
    });
  }

  calculate(): void {
    // 执行你的保存/计算逻辑
    console.log('提交的表单数据:', this.calculateForm.value);
    
    // 禁用表单,使其不可编辑
    this.calculateForm.disable();
  }
}

方法2:用变量动态控制readonly属性

如果不想使用表单禁用(比如需要自定义只读样式),可以定义布尔变量,点击按钮后切换状态,动态控制输入框的readonly属性。

修改后的模板代码

<form [formGroup]="calculateForm">
  <div class="form-group row">
    <p for="inputFrom" class="col-sm-4">Distance traveled(km):</p>
    <div class="col-sm-4">
      <input type="text" numbersOnly class="form-control form-control-md"
             formControlName="distance" [readonly]="isFormReadOnly">
    </div>
  </div>

  <button type="button" (click)="calculate()" class="btn btn-success"
          [disabled]="isFormReadOnly">
    {{ 'Save' | translate }}
  </button>
  <br>
</form>

组件TS代码

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  calculateForm: FormGroup;
  isFormReadOnly = false; // 默认表单可编辑

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.calculateForm = this.fb.group({
      distance: ['']
    });
  }

  calculate(): void {
    // 执行你的保存/计算逻辑
    console.log('提交的表单数据:', this.calculateForm.value);
    
    // 切换为只读状态
    this.isFormReadOnly = true;
  }
}

注:已修正原模板中翻译语法的错误({{'Save | translate }}改为{{ 'Save' | translate }})。

内容的提问来源于stack exchange,提问作者Jkerasr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:41:56