Angular 7: Show selected value upon clicking Radio button

I am having an issue with a radio button where I need to display a value when it is clicked. For example, when the "weekly" option is selected, I want it to display "Weekly" in the "Selection" element. I have tried to implement this but it is not working as expected. Can someone guide me on what changes I need to make to achieve this?

Here is my code:

HTML

    <form [formGroup]="form" (ngSubmit)="submit()">

  <label *ngFor="let order of orders">
    <input formControlName="orders" type="radio" name="orders" [value]="order.id" />
    {{order.name}}
  </label>

  <br>
  <label *ngFor="let radiobutton of options">
    <input type="radio" class="justify-right" formControlName="options" name="options" [value]="radiobutton.id">{{radiobutton.name}}
    </label>

   <p>Selection: {{options.name}}</p>
  <button>submit</button>
</form>

And here is my component code:

TS

    // Component logic goes here

For reference, please visit here.

Any help or guidance would be greatly appreciated.

Thank you!

Answer №1

If you wish to utilize this data beyond just displaying it, consider implementing ngModel. Here is how you can do so in your scenario:

Update your input as follows:

<input [(ngModel)]="selection" type="radio" class="justify-right" formControlName="options" name="options" [value]="radiobutton.id">

Next, include this code snippet in your typescript file under the 'options' section:

selection: String;

Alter your selection print statement to look like this:

Selection: {{selection}}

Now, if you need to access this value within any of your TypeScript functions, simply refer to it using this.selection

Answer №2

To make a simple modification, all you have to do is change a single line of code.

Replace it with the following:

<p>Choice: {{options.name}}</p>

Right underneath that,

<p>Selection: {{form.controls['options'].value}}</p>

Answer №3

When your formcontrol is associated with a formGroup, you won't be able to access options form control using options.name directly. Instead, you should utilize getters for easy access.

Getters are handy for accessing aliases within the form control instance without having to repeatedly use form.get('options') method for each instance.

get Options(){
        return this.form.get('options').value;
 }

Reference:https://angular.io/guide/reactive-forms#step-3-accessing-the-formarray-control

Example:https://stackblitz.com/edit/angular-dynamic-radio-list-pyad5s

Answer №4

To access the options directly in the HTML, you have two options. You can either use the form variable or create a getter in your component to display the selected value.

Using form variable:

<p>Selection: {{form.get('options').value}}</p>

Using a getter in the component:

Component:

get optionsValue() {
  return this.form.get('options').value;
}

HTML:

<p>Selection: {{optionsValue}}</p>

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

Exploring the latest features of Angular 13 alongside a useful NPM module that utilizes

I have encountered an issue with my date-picker module for Angular that involves importing moment.js. The problem arises when I import the NPM package moment-es6, which imports moment.js in the following way: import * as moment from "moment"; ...

Creating JSON files automatically when saving Angular 4 CLI projects in Visual Studio 2017

Just dipping my toes into Angular 4, I decided to start with VS 2017 for its integrated Angular support. NPM Task Runner has been handy for running NG BUILD alongside project builds. However, is there a method to see changes reflected in the JSON file wit ...

Issue encountered: NullInjectorError - R3InjectorError has been caused by a problem within AppModule regarding InjectionToken HTTP_INTERCEPTORS linking to TransferState

Error Image:- Error Images I am encountering this error: ERROR NullInjectorError: R3InjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> [object Object] -> TransferState -> TransferState -> TransferState]: NullInjectorError: No provider ...

Emulating Data in Angular 2 Using Configuration Similar to Ember Mirage

Is there a way to mock data through configuration in Angular 2 similar to how it's done in Ember Mirage? I'm aware that I can create my own solution using Dependency Injection and MockBackend to intercept HTTP calls and provide dummy data. Howeve ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

The TypeScript function was anticipating one argument, however it received two instead

Can you help me fix the issue with my createUser() function? Why am I unable to pass parameters in Smoke.ts? Login.ts : interface User { url: string, email: string, } class Test{ async createUser(user: User) { await Page.setUrl(user.url); aw ...

Setting up Microsoft Clarity for your Angular app on localhost is a simple process

Currently, I am attempting to set up Microsoft Clarity on my Angular app to run on localhost. After creating a new project on the Microsoft Clarity portal and specifying the URL as localhost (I also tried using localhost:4200</code), I copied the scrip ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but I’m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...

Is there a method to enable the acceptance of both dots and commas as decimal markers in input fields?

Hey there! I have a question for you. Is there a way to allow users to input both commas and dots as decimal markers, but still display the value with dots and remove thousand separators? For example, when a user inputs "123456,78", they should see "123 ...

Tips for accessing a variable from a Global service in Ionic

I am currently working on developing an app using Ionic but experiencing some difficulties. I encountered an issue while trying to access a variable from a global service when it is imported to another page. Here is an example of the Global service (backen ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

What causes the error message saying 'undefined' cannot be assigned to the specified type ...?

I just finished developing an innovative Angular application. Within the app.component.html file, I have included: <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedul ...

What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order: aaa, aa, a, bbb, bb, c. this.array= this.array.sort((n1, n2) => ...

When it comes to TypeScript, it feels like my interface can accept anything I throw at it, and it struggles to grasp how I've implemented and imported redux-toolkit and styled components

My Current Struggle: Errors in Typescript are occurring seemingly at random. The interface in my index.tsx file doesn't align with the object it should describe, yet no red flags are raised. On top of that: An error pops up when attempting to import ...

Local environments in Angular do not support file replacement

Within my angular.json file, I have set up configurations for both development and production environments. My goal is to prevent file replacement from occurring when running locally with 'ng serve', but allow it during Docker builds. Is there a ...

Tips for arranging the items within the slider according to the specified direction (rtl, ltr) in the Owl Carousel slider for Angular

Is there a way to dynamically change the direction of the owl-carousel-o angular slider based on the selected language? Currently, I have set rtl: true in the owl-carousel configuration during initialization. However, when the user switches to a different ...

I have chosen not to rely on Media Query for ensuring responsiveness in my Angular 2 application, and instead opted to utilize JavaScript. Do you think this approach is considered a

I am in the process of ensuring that my app is fully responsive across all screen sizes. Instead of relying on Media Query, I have chosen to use JavaScript with Angular 2 to achieve this responsiveness, utilizing features such as [style.width], *ngIf="is ...

What is the best way to configure Angular viewProviders when using an NgForm in a unit test?

One of the challenges I faced was with an Angular 16 component that required the form it will be placed inside as input. The solution came from using the viewProviders property, which I discovered through a helpful response to a question I had asked previo ...

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

Having trouble retrieving features from a QR code generated with Angularx-qrcode?

I utilized angularx-qrcode in order to create a QR code that displays data from qrInfo. However, I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading 'qrcElement') The code within qr-code-gener ...