Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Hide Then Show Control In Angular 4 Reactive Form Using Select

Tags:

angular

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() {}
}
like image 207
Paul D. Avatar asked Dec 11 '22 10:12

Paul D.


1 Answers

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

like image 129
Huangism Avatar answered May 23 '23 02:05

Huangism