A guide to dynamically display input fields according to the selected mat-radio button in Angular Material

I am currently utilizing angular material version 9.2.4

Within my project, I am implementing the angular material mat radio button with an input field. Each payment method will have its own corresponding input field. When the 'Cash' option is selected, it should display one input field while hiding the input fields for other methods.

Can anyone provide guidance on how to dynamically show the input field based on the selection of the mat radio button?

https://i.sstatic.net/YEzhX.jpg

My Code
<mat-radio-group class="text-left">
    <div class="form-group">
        <mat-radio-button class="ft-12" *ngFor="let item of itemsList" value="{{item.name}}" (change)="onItemChange(item)">
            {{item.name}}
            <input type="text" class="form-control" placeholder="0">
        </mat-radio-button>
    </div>
</mat-radio-group>

Answer №1

Check this out for a solution...

Inside your component.ts file

Assuming this is your itemsList

itemsList = [
  {name: 'Cash'},
  {name: 'cheque'},
  {name: 'Credit Card'},
  {name: 'Cash Voucher'},
];

  isVisible = -1; // Set to show specific input by default, change to index of item in itemsList array

onItemChange(item, i) {
   console.log({item, i});
   this.isVisible = i;
}

In your component.html file

<mat-radio-group class="text-left">
     <div class="form-group">
        <mat-radio-button class="ft-12" *ngFor="let item of itemsList; let i = index;" value="{{item.name}}" (change)="onItemChange(item, i)">
              {{item.name}}
       <input type="text" *ngIf="isVisible == i" class="form-control" placeholder="0">
        </mat-radio-button>
     </div>
</mat-radio-group>

See the outcome below

Radio 1

https://i.sstatic.net/OjHoY.png

Radio 2

https://i.sstatic.net/YBkE6.png

This should help resolve your problem.

Answer №2

demo

<mat-radio-group class="text-left">
    <div class="form-group">
      <mat-radio-button class="ft-12" *ngFor="let item of itemsList" value="{{item.name}}" (change)="onItemChange(item)">
        {{item.name}}
       
      </mat-radio-button>
      
    </div>
  </mat-radio-group>
   <input *ngIf="selectedItem.name=='cash'" type="text" class="form-control" placeholder="0">

component.ts

export class UniqueComponent implements OnInit{ 
   selectedItem:  any={} ;  
    eventForm: FormGroup;
    itemsList=[];
  public toggleDisplay:boolean;

  ngOnInit(){
       this.eventForm = new FormGroup({          
      'completed': new FormControl()
      });      
    
this.itemsList=[{
  item:'check',
  name:'check'
},
{
  
  item:'cash',
  name:'cash'

}
]
  }
  onItemChange(item:any){
this.selectedItem=item
  }
  
}

Answer №3

To ensure that the radio button value is always saved when clicked, you can maintain a variable to store the selected option and use an *ngIf directive within the input tags. Here's a modified version of your code:

<mat-radio-group class="text-left">
    <div class="form-group">
      <mat-radio-button class="ft-12" *ngFor="let item of itemsList" value="{{item.name}}" (click)="selectedField={{item.name}}">
        {{item.name}}
        <input *ngIf="selectedField==item.name" type="text"  class="form-control" placeholder="0">
      </mat-radio-button>
    </div>
  </mat-radio-group>

Don't forget to add this variable in your ts file:

selectedField: string;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to empty an angularJS array

let itemList = ['X', 'Y', 'Z']; Even though the array is cleared, the user interface does not reflect the change. itemList = []; This method solves the issue. But why? itemList.length = 0; ...

Submit a collection of images and an object to the server using ReactJS

I'm currently working with Reactjs on the frontend. In order to set the profile picture to state, I've implemented the following code: handleImageChange = (event) => { event.preventDefault(); var file = event.target.files[ ...

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

API response containing JSON data is not being displayed properly in the webdatarocks angular component

I can't seem to figure out how to properly display the JSON formatted data returned by a REST API using Angular. Any suggestions on how to accomplish this? Here's what I've been attempting to do - fetchData() { this.service.fetchData().s ...

Obtaining Beverage Overall with Loop

I am currently using a function to calculate the total of each drink, with a total of 5 drinks: var totalEstimate = 0; var locoCost = 0; var blackCost = 0; function calcLoco() { totalEstimate -= locoCost; locoCost = docume ...

Django app with Vue.js integration is throwing a 405 error for Axios PUT request

I have a project in progress for managing inventory on a small scale. One of the functionalities I'm working on involves updating the stock quantity when a product is withdrawn. I've encountered an issue while using Axios and the .put() function, ...

The Instagram Basic Display API encounters an issue when processing a request for a user profile that does

Following the migration of our code from legacy api to basic display, we encountered an issue where no media is being retrieved for users who have not set their age in their profile. Instead, we are consistently receiving the following error: { "err ...

Unable to make changes to the text within the textarea field

Currently, I am in the process of creating a script to streamline the tedious task of providing teaching feedback. To scrape data such as student names and classes, I am utilizing selenium/python. While everything is running smoothly, I have encountered an ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

What is the solution to the error message Duplicate identifier 'by'?

While conducting a test with the DomSanitizer class, I made some changes and then reverted them using git checkout -- .. However, upon doing so, I encountered a console error: Even after switching to a different git branch, the error persisted. Here are ...

Confirming the structure of a URL using JavaScript/jQuery

I have a text field where users input URLs. I need to validate the format of the URL using regular expressions. Specifically, I am looking for invalid URLs such as: http://www.google.com//test/index.html //Invalid due to double slash after hostname http: ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

Aurelia: The passing down of views and view-models

In the process of developing an Aurelia app, I am tasked with creating functionality that allows users to display various lists for different resources. These lists share common features such as a toolbar with search and refresh capabilities, along with a ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Tips for transferring information between service functions in Angular

In my front-end development, I am working on creating a store() function that adds a new question to the database. However, I need to include the active user's ID in the question data before sending it to the back-end. Below is the code for the store ...

JavaScript popup confirmation in an MVC3 AJAX form

I have implemented an ajax form in a MVC3 project and I am looking for a way to incorporate a JavaScript confirm popup upon clicking the submit button. While I have managed to get the popup to display, I am struggling to prevent the form submission if the ...

tips for passing value to the date field using proctractor

This is the HTML code I am working with: <input id="filter-datepicker" type="daterange" ranges="ranges" class="form-control date-picker" placeholder="Select Date Range" name="sensorDetails.date" ng-model="myDateRange" ranges="ranges" requi ...

What is the best way to grab just the whole number from a string in JavaScript?

I'm facing an issue with a specific string format: const value = "value is 10"; My goal is to retrieve the integer 10 from this string and store it in a separate variable. How can I achieve this efficiently? ...