-2

I have two radio buttons in my template. on selecting a button, different input text fields should be displayed for each button and the other fields should hide.

How can I do this using Angular?

I have tried using *ngIf and ngModel, but not able to solve this problem.

ng-hobby
  • 2,077
  • 2
  • 13
  • 26

1 Answers1

0

Take a look:

Source Code, StackBlitz

Demo

HTML

Type 1: <input type="radio" name="foo" value="type_1" [(ngModel)]="radioBtn">

<br>

Type 2: <input type="radio" name="foo"
 [(ngModel)]="radioBtn" value="type_2">

<br>

<ng-container *ngIf="radioBtn == 'type_1'">
    Type 1: <input type="text" placeholder="Type 1">
</ng-container>

<ng-container *ngIf="radioBtn == 'type_2'">
    Type 2: <input type="text" placeholder="Type 2">
</ng-container>

TS

export class AppComponent  {
  radioBtn: string = 'type_1';
}

Explanation:

To make radio buttons work, you need two things:

  1. You need to set the same name to all the radio buttons belonging together name="foo"
  2. You need to specify the value for each of those radio buttonsvalue="bar"
Abhijit Kar ツ
  • 1,732
  • 1
  • 11
  • 24