5

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() {}
}
4
  • 3
    [hidden]="myForm.controls.isNameOnly.value == 'true'" plnkr.co/edit/7ub2fy7CBdBA46i4qkvv?p=preview your values in select are true and false in string form so just check for the string true Commented Jul 27, 2017 at 17:47
  • @Huangism your version is better :) Commented Jul 27, 2017 at 17:50
  • @Vega feel free to update your answer with this alternative solution Commented Jul 27, 2017 at 17:51
  • I was going to ask you to post your answer and explain it as I am thrilled by 'true'. How it came a string? Commented Jul 27, 2017 at 17:53

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.