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.
Here is the template for the component:
<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>
Here is the definition of the component:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With