Angular 2动态禁用FormControl

时间:2018-07-26 08:20:07

标签: angular

我有一个简单的表单组,带有2个表单控件。最初,两个控件都需要进行验证。

模板中还有一个按钮。当单击按钮时,我想更改表单组的行为。即,两个控件都必须禁用,并且验证也需要删除。

StackBlitz

import {
  Component,
  AfterViewInit,
  ViewChild
} from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  name = 'Angular 6';

  form: FormGroup;

  constructor(private fb: FormBuilder) {

    let username = this.fb.control.apply(null, [{
      value: 'gannr',
      disabled: false
    }, Validators.required])

    let password = this.fb.control.apply(null, [{
      value: 'hello',
      disabled: false
    }, Validators.required]);

    this.form = this.fb.group({
      username: username,
      password: password
    });


  }


  changeFormBehavior() {

    let username = this.fb.control.apply(null, [{
      value: 'gannr disabled',
      disabled: true
    }]);

    let password = this.fb.control.apply(null, [{
      value: 'hello',
      disabled: true
    }]);

    this.form = this.fb.group({
      username: username,
      password: password
    });

  }



}

1 个答案:

答案 0 :(得分:1)

也许您使用了正确的变量和语法...

  changeFormBehavior() {
    this.form.get('username').disable();
    this.form.get('password').disable();
    this.form.get('username').setValidators(null);
    this.form.get('password').setValidators(null);
 }

Stackblitz