无法隐藏然后使用Select以Angular 4反应形式显示控件 [英] Can't Hide Then Show Control In Angular 4 Reactive Form Using Select
问题描述
我无法使用嵌入Angular 4反应形式的选择在隐藏和显示控件之间切换.下面显示了该问题: https://plnkr.co/edit/s7wYqy3Oa9eGmvOY3sNX?p=preview .如果选择名称"选项,则地址字段将按预期隐藏.如果此后选择名称和地址"选项,则不会显示.
I am unable to toggle between hiding and showing a control using a select embedded in an Angular 4 reactive form. The following shows the issue: https://plnkr.co/edit/s7wYqy3Oa9eGmvOY3sNX?p=preview. If you select the "Name" option, the address field will be hidden as expected. If you select the "Name and Address" option afterwards, it does not show.
这是组件的模板:
<form [formGroup]="myForm" novalidate="">
<div class="form-group">
<label>Choose</label>
<select class="form-control" formControlName="isNameOnly">
<option *ngFor="let option of options" [value]="option.value">
{{option.name}}
</option>
</select>
</div>
<div class="form-group">
<label>Name</label>
<input class="form-control" formControlName="name" />
</div>
<div class="form-group" [hidden]="myForm.controls.isNameOnly.value">
<label>Address</label>
<input class="form-control" formControlName="address" />
</div>
<pre>{{myForm.controls.isNameOnly.value}}</pre>
</form>
这是组件的定义:
import { Component, Input, OnChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-form',
templateUrl: './form.component.html'
})
export class MyFormComponent implements OnChanges {
myForm: FormGroup;
options = [
{name: 'Name Only', value: true},
{name: 'Name and Address', value: false}
];
constructor(
private fb: FormBuilder
) {
this.myForm = this.fb.group({
name: '',
address: '',
isNameOnly: false
});
}
ngOnChanges() {}
}
推荐答案
更新为隐藏以下内容,检查真实字符串
Update hidden to the following checking the true string
[hidden]="myForm.controls.isNameOnly.value == 'true'"
https://plnkr.co/edit/7ub2fy7CBdBA46i4qkvv?p=preview
我相信myForm.controls.isNameOnly.value
返回一个字符串,并且[hidden]
将其作为表达式求值,并且由于"true"或"false"都是非空字符串,因此隐藏始终为true
I believe myForm.controls.isNameOnly.value
returns a string and [hidden]
evaluates it as an expression and since "true" or "false" are both non empty strings, so hidden is always true
这篇关于无法隐藏然后使用Select以Angular 4反应形式显示控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!