禁用角度2反应形式的文本输入

时间:2018-05-31 15:19:11

标签: angular angular2-forms angular-reactive-forms

我在角度2中有一个反应形式,可以通过添加按钮调用新表单或编辑按钮来更新现有详细信息。如果用户选择编辑按钮,则应禁用电子邮件输入。我有下面的代码,但只要用户选择编辑,输入就不会被禁用。如果我在addForm方法中将disabled设置为true并选择编辑按钮,则禁用电子邮件输入



    public addForm(event: string) : FormGroup {

            this.userForm = this.fb.group({
                firstName: ['',
                    [   Validators.required,
                        Validators.maxLength(ManageUsersConstants.maxLengthName)
                    ]],
                lastName: ['',
                    [   Validators.required,
                        Validators.maxLength(ManageUsersConstants.maxLengthName)]
                    ],
                email: [{value: '', disabled : false}],
                }),
            });
        }
  

    public editForm(event: string, editValues : any) : FormGroup {
        this.userForm = this.fb.group({
            firstName: [editValues.firstName, [
                Validators.required,
                Validators.maxLength(ManageUsersConstants.maxLengthName)]],
            lastName: [editValues.lastName,
                [   Validators.required,
                    Validators.maxLength(ManageUsersConstants.maxLengthName)]],
            email: [{value: editValues.email, disabled: true}],
        });

    }




1 个答案:

答案 0 :(得分:1)

在编辑活动中添加以下代码this.formGroup.controls['email'].disable() ;

<强> Component.ts

 ngOnInit() {
    this.formGroup = this.formBuilder.group({
      email: [{value: '', disabled : false}]      
    });  
  }  

  onEdit(){    
    this.formGroup.controls['email'].disable()   
  }

<强> HTML

<form [formGroup]="formGroup" (ngSubmit)="onSubmit()" #form>
    <div>
      <label for="dateone">Email: </label>
      <input formControlName="email" #email/>          
      <button type="button" (click)="onEdit()">edit</button>  
      </div>
</form>

Stackblitz demo