Search code examples
htmlangularformstypescriptangular-ng-if

Angular ngIf formGroup


I have a form on Angular that allows to display an input according to the value selected in a drop-down list.

Here is an example of my code:

(If two is selected an input appears)

https://stackblitz.com/edit/angular-fqkfyx

If I leave the [formGroup] = "usForm" the input display does not work. On the other hand if I delete [formGroup] = "usForm" of the tag form my code works as I want. So the problem is related to [formGroup] = "usForm"

My html:

 <div class="offset-md-2">
  <form [formGroup]="usForm">
    <div class="div-champs">
      <p id="champs">Type
        <span id="required">*</span>
      </p>
      <div class="select-style ">
          <select [(ngModel)]="selectedOption" name="type">
              <option style="display:none">
              <option [value]="o.name" *ngFor="let o of options">
                {{o.name}}
              </option>
          </select>
      </div>
    </div>
    <p id="champs" *ngIf="selectedOption == 'two'">Appears
      <input type="appears" class="form-control" name="appears">
    </p>
  </form>
</div>

My component.ts:

import { Component, OnInit } from '@angular/core';

import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-create-us',
  templateUrl: './create-us.component.html',
  styleUrls: ['./create-us.component.css']
})
export class CreateUsComponent implements OnInit {

  public usForm: FormGroup;
  public selectedOption: string;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.usForm = this.fb.group({
      'type': [null, ],
      'appears': [null, ],
    });
  }

  options = [
    { name: 'first', value: 1 },
    { name: 'two', value: 2 }
  ];
}

I simplified my problem as much as in reality it is in a large form with a dozen input

I need your help, thanks in advance

Regards, Valentin


Solution

  • You should be using formControlName instead of [(ngModel)].

    And then in comparison, you should be comparing to usForm.value.type instead of the selectedValue.

    Give this a try:

    <div class="offset-md-2">
      <form [formGroup]="usForm">
        <div class="div-champs">
          <p id="champs">Type
            <span id="required">*</span>
          </p>
          <div class="select-style ">
              <select formControlName="type" name="type">
                  <option style="display:none">
                  <option [value]="o.name" *ngFor="let o of options">
                    {{o.name}}
                  </option>
              </select>
          </div>
        </div>
        <p id="champs" *ngIf="usForm.value.type == 'two'">Appears
          <input type="appears" class="form-control" name="appears">
        </p>
      </form>
    </div>
    

    Here's a Sample StackBlitz for your ref.