Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 如何禁用表单 #95

Open
deepthan opened this issue Sep 10, 2020 · 0 comments
Open

Angular 如何禁用表单 #95

deepthan opened this issue Sep 10, 2020 · 0 comments
Labels

Comments

@deepthan
Copy link
Owner

方法1: 直接设置为false

export class AppComponent {
  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      input: new FormControl(false),
    });
  }
}

方法2: 设置disabled 为 false

export class AppComponent {
  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      input: new FormControl({ disabled: true, value: '' }, []),
    });
  }

}

方法3 使用指令

指令ts

import { NgControl } from '@angular/forms';

@Directive({
  selector: '[disableControl]'
})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {
  }

}

html中使用 [disableControl],当然也可以传变量进去

<form [formGroup]="form">
  <input formControlName="input1" placeholder="输入框1" [disableControl]="true">
  <input formControlName="input2" placeholder="输入框2" >
</form>
@deepthan deepthan added the form label Sep 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant