在Angular 4中尚未选择第一选择选项时禁用第二选择选项

问题描述 投票:-1回答:2

当我没有选择我的第一个选择选项时,如何禁用我的第二个选择选项和输入值?就我而言,我的第一个选择选项是“选择成分”。我在“选择成分”中有一个事件,如果订阅并且结果成功,那么第二个选择选项和输入值应该被启用?这里是我所做的stackblitz代码。

https://stackblitz.com/edit/angular-rgxfsa?file=app/app.component.ts

onSelectIngredient(event): void {
   const ingredient_id =  this.productForm.get('ingredient_id').value
    // this.subscription = this.ingredientService.selectIngredient(ingredient_id)
    // .subscribe(
    //       (data:any) => {
    //         this.ingredient = data;     
    //       },
    //       error => {
    //        console.log(error);
    //       })
  }
angular angular-reactive-forms angular4-forms
2个回答
0
投票

最初通过以下代码禁用第二个表单:

this.productForm.controls["topping_id"].disable();

当第一个下拉列表更改时,然后通过以下代码启用控制:

this.productForm.controls["topping_id"].enable(); 

希望它会有所帮助。


1
投票

您可以先监听禁用topping_id控件,然后通过订阅其控制valueChange Observable来监听ingredient_if选择。

 this.productForm = this.formBuilder.group({
      ingredient_id: new FormControl(null, Validators.required),
      topping_id: new FormControl({ value: null, disabled: true }, Validators.required), // <- here initial disable
      input_value: new FormControl(null, Validators.required),
 });

// listen to ingredient valueChange to enable the topping
this.productForm.get('ingredient_id').valueChanges.subscribe(value => {
  if (value) {
    this.productForm.get('topping_id').enable();
  } else {
    this.productForm.get('topping_id').setValue(null);
    this.productForm.get('topping_id').disable();
  }
});

选择ingredient_id值后,您可以手动启用顶部控制。

Here is a forked stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.