简体   繁体   English

在反应性表单/ Angular 4+中禁用选择表单控件

[英]Disabling a Select Form Control in Reactive Forms/Angular 4+

I am trying to disable a select form control in my reactive form. 我正在尝试在反应式表单中禁用选择表单控件。 Is there any issues with this currently? 目前有什么问题吗? I have been looking around for an answer but I am unable to get a straight answer. 我一直在寻找答案,但无法获得直接答案。 The code I am using works fine if it is a regular input control, but not for a select control. 如果我使用的代码是常规输入控件,而不是选择控件,则可以正常使用。

<select id="locationScanType" class="form-control" formControlName="locationScanType">                     
  <option value="0">-- Select One --</option>
  <option value="FACILITY">Facility</option>
  <option value="CUSTOMER_LOCATION">Customer Location</option>
  <option value="MY_LOCATION">My Location</option>
</select>

<input type="text" class="form-control" formControlName="textInput" /> 

In my ngOnInit() function I do this: 在我的ngOnInit()函数中,我这样做:

this.stopForm = this._formBuilder.group({
  locationScanType: { value: this.stop.locationScanType, disabled: true }, // Hard code true for demo
  textInput: { value: 'Text Input', disabled: true }
});

The disabled attribute works for the text input, but doesn't for the select input. disabled属性适用于文本输入,但不适用于select输入。 It does select the correct value for the select input, but doesn't disable it. 它会为选择输入选择正确的值,但不会禁用它。 Am I missing something obvious? 我是否缺少明显的东西?

I can disable the select input by using the [attr.disabled] and/or [ngClass] attributes on the select input, but I'd rather do it in the form builder; 我可以通过在选择输入上使用[attr.disabled]和/或[ngClass]属性来禁用选择输入,但是我宁愿在表单构建器中执行此操作; not to mention if I don't, Angular throws a warning into my browser's console. 更不用说,如果我不这样做,Angular会向浏览器的控制台发出警告。

typescript: 2.4.2

@angular/core: 5.1.3

@angular/forms: 5.2.0

you can use the disable function that provide the FormControl class. 您可以使用提供FormControl类的disable函数。 once you have the form created you can call this function in the specific form control 一旦创建了表单,就可以在特定的表单控件中调用此函数

this.stopForm = this._formBuilder.group({
  locationScanType: { value: this.stop.locationScanType }, // Hard code true for demo
  textInput: { value: 'Text Input', disabled: true }
});

this.stopForm.get("locationScanType").disable()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM