Selecting options with a click of a button in Template-Driven Forms

Whenever the page loads, I always notice that the last radio button is automatically checked. I believe it has something to do with the Id attribute, but I'm struggling to find a solution.

countryArray

countryA = [{name : "Finland"}, {name : "china"},{name: "USA"}]

test.html

            <form #filterForm="ngForm" (ngSubmit)="addFilter(filterForm)" autocomplete="off">
                <div class="row">
                    <div class="col-12" style="border: 1px solid red">
                        <div *ngFor="let x of country">
                            <label for="{{x.name}}"> {{x.name}} </label>
                            <input type="radio" id="{{x.name}}" value="{{x.name}}" name="countries" [(ngModel)]='x.name' >
                        </div>
                    </div>
                    <!-- <div class="col-12" style="border: 1px solid red">b</div>
                    <div class="col-12" style="border: 1px solid red">c</div>
                    <div class="col-12" style="border: 1px solid red">D</div> -->
                </div>
            </form>
            hh : {{filterForm.value | json}}

Answer №1

To make use of ngModel for the value of radio button, it is recommended to add a selected property to each country:

In the constructor:

this.country = this.country.map(item =>({ name: item.name , selected : false }));

In the HTML:

<div class="col-12" style="border: 1px solid red">
    <div *ngFor="let x of country; index as i">
        <label for="{{x.name}}"> {{x.name}} </label>
        <input type="radio" id="{{x.name}}" value="{{x.name}}" name="countries" [(ngModel)]="country[i].selected">
    </div>
</div>

Check out the demo.

Answer №2

Applying the ngModel attribute to 'x.name' is what causes it to be checked. To resolve this, you can create a variable named selectedRadio and assign the value of the radio button to it:

<div *ngFor="let x of country">
    <label for="{{x.name}}"> {{x.name}} </label>
    <input type="radio" 
        id="{{x.name}}" 
        value="{{x.name}}"
        [(ngModel)] ="selectedRadio"
        name="countries">
</div>
<p> {{ selectedRadio | json }} </p> 

In TypeScript, define the variable as follows:

selectedRadio: any;

You can view an example on stackblitz here.

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

Why State in React Does Not Get Updated When Parent Function is Called from Child Component?

Struggling with getting my child component, ChildButton, to trigger a function in its parent component, ParentTable, that includes a "setState" to refresh or update the table in the parent. I've passed a getData function from the parent to the child ...

Using vue-resource to intercept an ajax error and catching the "Uncaught (in promise)" exception

I am utilizing vue-resource to retrieve data from the server. In order to access the correct data, a user must possess a JWT token. If the token is invalid or has expired, a status code of 401 will be returned. Similarly, if a user attempts to reach a forb ...

Encountering a Typescript error when attempting to access the 'submitter' property on type 'Event' in order to retrieve a value in a |REACT| application

I am facing an issue with my React form that contains two submit buttons which need to hit different endpoints using Axios. When I attempt to retrieve the value of the form submitter (to determine which endpoint to target), I encounter an error while work ...

A guide to effectively utilizing spread props in React with Typescript and styled-components

As I develop a UI component for my application to ensure consistent styling, I require access to spread props for functionalities like value, onChange, and more. This is the current structure of my TextInput component: import { DetailedHTMLProps, InputHTM ...

Ways to display or conceal a component based on the current component being used

I am a newcomer in Angular, and I believe finding the solution to my problem will be a great learning experience. In my default component, the MainComponent is loaded in my <router-outlet>. At this stage, both the menu and the footer are displayed. H ...

Encountering Next.JS Router Issue: Unable to Access Properties of Null (specifically 'useContext')

As a beginner in Next.js and React, I'm facing an issue with redirecting users from the "Projects" page to the Product Page Details. Here's the code snippet I am using: const openProjectDetails = () => { Router.push('/api/' + props ...

Step-by-step guide on adding data to an arraylist using JavaScript

My ajax callback function receives a json object (arraylist parsed into json in another servlet) as a response, and then iterates through it. Ajax section: $.ajax({ url:'ServiceToFetchDocType', data: {" ...

Interactive canvas artwork featuring particles

Just came across this interesting demo at . Any ideas on how to draw PNG images on a canvas along with other objects? I know it's not a pressing issue, but I'm curious to learn more. ...

Ajax disregards the endless scroll material that has been injected into the DOM

I am currently facing an issue with loading posts on a page using foreach and the paginate function in Laravel. I have set up infinite scrolling through the posts, with each post having its own unique form. The first posts that load without JavaScript scro ...

Encountering a JavaScript issue where the error "function is undefined" appears when attempting to import the GL

I'm a beginner in Javascript and I'm currently working on a project that involves displaying a 3D model in a modal. Everything was running smoothly until I attempted to include an import statement. Once I added the line import {GLTFLoader} from & ...

Is it possible to incorporate a label within a dropdown menu (<select>)?

How can I add a label inside a select box using Bootstrap? Here is an example: Before selecting an option After selecting an option, the label should appear in a small size like this: After selecting an option : <div class="form-group"> & ...

Hover over to reveal the button after a delay

I'm struggling with implementing a feature in my Angular code that displays a delete button when hovering over a time segment for 2 seconds. Despite trying different approaches, I can't seem to make it work. .delete-button { display: none; ...

Securing my private key on a webpage from potential exposure by mandrillapp

After successfully creating and adding the key in Mandrill, I am able to send emails from my JavaScript page hosted at this link: However, I am facing an issue where my Mandrill key is publicly visible (in the contact_me.js file). I attempted to restrict ...

Choose the appropriate NPM module platform for Angular development

My Angular application runs smoothly in Chrome, but encounters errors on Internet Explorer. The issue arises from the different distributions of NPM modules I install. For instance, within the kendo-angular-charts folder, we have: - dist |- cdn |- e ...

Differences Between Javascript Objects and JScript Dictionaries

When it comes to Javascript Objects and JScript Dictionaries, both are considered associative arrays. obj = new Object ; dic = new ActiveXObject("Scripting.Dictionary") ; My main inquiry is whether there are any differences between them in efficiency, wh ...

Angular rest call is returning an undefined response object attribute

When attempting to retrieve the attribute of a response object, it is returning as "undefined". var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', function($scope, $http) { $scope.addNewChoice = functio ...

Three.js: Modifying values within dat.GUI is not allowed

I have added a "comboBox" to my dat.GUI instance in order to select possible values. However, when I run my application, the dat.GUI appears with the comboBox but it seems to be frozen - I cannot change its default value. Below is the code snippet that dem ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

Using Three.js to incorporate an external JavaScript file into an HTML document

Currently experimenting with three.js and successfully rendered a 3D cube using HTML. Here's a snippet of the HTML code: <div id="render" class="center-block"> <script> // JavaScript code for rendering the 3D cube goes here </script&g ...

If the parameter type is "never", the ReturnType will be "any"

short tale const xyz = (a:never):number=>1 type b = ReturnType< typeof xyz> //any const xyz2 = (a:number, b:never):number=>1 type b2 = ReturnType< typeof xyz2> //any playground If any parameter type is never, the ReturnType becom ...