Angular2 Reactive Forms - Disable form control dynamically from condition

前端 未结 5 710
感情败类
感情败类 2021-02-07 08:05

I have a select control that I want to disable dynamically based on a condition:

this.activityForm = this.formBuilder.group({
  docType: [{ value: \'2\', disable         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-07 08:10

    Since I don't know how you're manipulating activeCategory (maybe it's also a FormControl?), I'll suggest the following approach:

    You can use (change) to detect when this.activeCategory has changed, as below:

    1 - If you're using ngModel:

    
    

    2 - If it's a FormControl:

    
    

    So, in component, you can manipulate the docType control using disable/enable methods:

    checkValue(event: Event) {
      const ctrl = this.activityForm.get('docType');
    
      if (event.value === 'document') {
        ctrl.enable();
      } else {
        ctrl.disable();
      }
    }
    

提交回复
热议问题