FormControl disabled is not working with logic

2019-08-09 09:52发布

问题:

I want to make a field disabled from ts file. it is working fine when I true/false statically. but I want to make it logically. when my form in edit mode I will make the fields editable. when the form in view mode will disable the fields.

It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors.

  Example: 
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

Logic when i change the mode

editProspectDetails() {
    this.editProspectMode = !this.editProspectMode;
    this.isProspectDisabled();
}

FormControl Name:

this.fb.group({
prospect_pref_name: new FormControl({value: '', disabled: this.isProspectDisabled()}),
})

isProspectDisabled(){
    return true; // working

    but i want to make it conditionally
    console.log(this.editProspectMode); // it will return : true/ false
    return this.editProspectMode;
}

回答1:

You can simply use disable() to disable field

try this

this.fb.group({
prospect_pref_name: new FormControl(''),
}

and in your editProspectDetails()

editProspectDetails() {
    this.editProspectMode = !this.editProspectMode;
    this.your_form_name.controls.prospect_pref_name.disable();
}