【发布时间】:2021-03-05 13:44:30
【问题描述】:
我有一个函数,它仅在之前的选择字段具有“其他”选定值时才显示输入字段:
inputMotor = 'none';
this.f.get('motorType').valueChanges
.subscribe((pVal) => {
pVal === 'Other' ? this.inputMotor = 'flex' : this.inputMotor = 'none';
});
还有模板:
<div class="form-group">
<label for="motorType">Motor Type</label>
<select class="form-control" formControlName="motorType" id="motorType" type="text">
<option value="">Choose the Motor Type</option>
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group" [ngStyle]="{'display':inputMotor}">
<input class="form-control" formControlName="otherMotorType" placeholder="Other Motor Type" type="text">
</div>
在上面的示例中,我使用该函数来识别“motorType”字段中的选定值。问题是此功能适用于许多选择字段。所以,我试图为此生成一个通用函数。在我的服务中,我尝试过:
getField(form, field: string, inputField: string) {
form.get(field).valueChanges
.subscribe((pVal) => {
pVal === 'Other' ? inputField = 'flex' : inputField = 'none';
});
}
要调用该函数,我会使用:
this.utils.getField(this.f, 'motorType', this.inputMotor);
对组件的调用会识别前两个参数,但不会更新变量(在示例中为 inputMotor),始终将其值保持为“none”,并且不显示“Other”字段。
我按照this post 中的建议进行了尝试,但它仅适用于单个变量(它不可重复使用)。
另外,我试图避免组件中的任何代码重复。因此,对于我拥有的每个表单,我只是尝试调用服务函数并传递必要的参数。
我怎样才能做到这一点?
【问题讨论】:
标签: javascript angular function angular-services angular-components