如何动态禁用/启用模板中的反应式表单?

问题描述 投票:0回答:1

我想根据组件的布尔输入禁用(或启用)FormGroup

export class MyFormComponent implements OnInit {
  form: FormGroup;
  @Input() isDisabled: boolean;

  ngOnInit(): void {
    this.form = this.fb.group({
    // ...

我发现的所有答案都说在模板中使用

<form [formGroup]="form" [disabled]="isDisabled"
以及在打字稿中使用
this.form.disable();
是不好的做法,其中大多数人也在使用旧版本的 Angular。

是否有任何好的解决方案可以在模板中执行此操作并避免使用最近的 Angular(16+)添加额外代码?

angular angular-reactive-forms angular-template
1个回答
0
投票

这可以通过

signal
来完成,基本上我们使用效果来在信号变化时执行逻辑,在此基础上我们使用
disableForm
enableForm
启用和禁用表单。

disableForm = signal(false);
...

...
constructor() {
  effect(() => {
    if (this.disableForm()) {
      this.form.disable();
    } else {
      this.form.enable();
    }
  });
}

完整代码:

import { Component, effect, signal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form">
      <input formControlName="test"/>
    </form>
    <button (click)="toggleDisabled()">toggle disable</button>
  `,
})
export class App {
  disableForm = signal(false);
  name = 'Angular';
  form = new FormGroup({
    test: new FormControl(1),
  });

    constructor() {
      effect(() => {
        if (this.disableForm()) {
          this.form.disable();
        } else {
          this.form.enable();
        }
      });
    }

  toggleDisabled() {
    this.disableForm.update((value: boolean) => !value);
  }

  ngOnInit() {}
}

bootstrapApplication(App);

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.