Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that the radio button could be checked by clicking on the label (which worked well in simple components). But in the MatDialog component, I can no longer check it on label click. Did I miss something? What could be causing this problem?

Thank you in advance for any insights!

Here is my app-new-review-modal.html:

<mat-dialog-content>
<form [formGroup]="rate">
    <div class="rating" > ;
      <input type="radio" value="5" name="rateStar" id="star5" formControlName="rateStar">
      <label for="star5"></label>
      <input type="radio" value="4" name="rateStar" id="star4" formControlName="rateStar">
      <label for="star4"></label>
      <input type="radio" value="3" name="rateStar" id="star3" formControlName="rateStar">
      <label for="star3"></label>
      <input type="radio" value="2" name="rateStar" id="star2" formControlName="rateStar">
      <label for="star2"></label>
      <input type="radio" value="1" name="rateStar" id="star1" formControlName="rateStar">
      <label for="star1"></label>
    </div>
  </form>
</mat-dialog-content>

This is my controller:

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

@Component({
  selector: 'app-new-review-modal',
  templateUrl: './new-review-modal.component.html',
  styleUrls: ['./new-review-modal.component.scss']
})
export class NewReviewModalComponent implements OnInit {
  rate: FormGroup;

  constructor(private fb: FormBuilder) {
    })

  }

  ngOnInit(): void {
    this.rate = this.fb.group({
      rateStar: []
    });
  }

}

If needed, here is the CSS:

.rating {
  width: 155px;
  display: flex;
  justify-content: space-between;
  font-size: 20px;
  direction: rtl;

  label {
    float: right;
    cursor: pointer;
    color: #676767;

    &:before {
      content: "\2605";
    }
  }

  input {
    display: none;
  }

  input:checked ~ label,
  label:hover ~ label,
  label:hover {
    color: rgb(120, 140, 116);
  }

}

Answer №1

Give this code a try:

import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  rate: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.rate = this.fb.group({
      rateStar: new FormControl()
    });

    this.setValue("4"); // default value
    }

    setValue(rateStar: string): void {
        this.rate.patchValue({ rateStar });
    }
}

You can retrieve your value in HTML using the following -

<p>
    {{this.rate.get('rateStar').value}}
</p>

Visit this link for a sandbox demonstration

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

Using Angular to Make a Request for a Twitter API Access Token

I'm facing some challenges while trying to implement a Twitter Sign-In method for my angular app. The issue seems to be with the initial step itself. I am attempting to make a post request to the request_token API by following the steps outlined at th ...

Having trouble with Angular Ng2-file-Upload's Upload.all() method not successfully sending files to the API

Dealing with the challenge of uploading files in mp4 and jpg formats, I have set up 2 separate instances of FileUploader with custom validation. Upon clicking the upload button, I attempt to merge the files from both instances into a single FileUploader ...

Encountering issues with MatToolbar in Angular 9 causes unexpected errors

Running Angular version 9.2.0 Encountering an issue while importing the MatToolbarModule in a module and utilizing it in the HTML template. The error message reads as follows: This could indicate that the library (@angular/material/toolbar) that declar ...

"Encountering an issue with mounting components in React Unit Testing with Jest and Typescript

Having developed a simple app with components, here is the code: import GraphicCanvas from './Graphing/GraphCanvas'; import { drawCircle } from './Graphing/DrawCircle'; function App() { return ( <div className="App"&g ...

Unknown Angular component identified

I'm currently working on an application with the following structure: app |-- author |-- |-- posts |-- |-- |-- posts.component.html |-- |-- author.component.html |-- |-- components |-- |-- tag |-- |-- |-- tag.component.ts |-- home |-- |-- home.comp ...

How can I ensure I am receiving real-time updates from a Resolver Service by subscribing and staying in sync with the

How can I effectively implement this code without encountering an error? "Property 'resolve' in type 'DocumentaryResolverService' is not assignable to the same property in base type 'Resolve'." import { Documentary } from ...

Errors may arise in Typescript when attempting to block the default behavior of DataGrid onRowEditStop

Hey there! I'm new to posting questions here and could use some help. I'm encountering a minor issue while trying to prevent the default behavior of the "Enter" key in the "onRowEditStop" method of the DataGrid component. Here's my code sni ...

What is the process for setting a push key while pushing data to a Firebase database?

When writing data to the Firebase database using both Angular 4 on the frontend and Firebase functions on the backend, a unique push key is generated by Firebase. This key makes it difficult to access the data in the future. I am curious if there is a way ...

Is there a way to extract a specific item from a ListView by tapping on it in Nativescript?

Attempting to retrieve data from a tap event using angular2 + typescript: This is the html code for the component: <RadListView row="1" [items]="groceryList" [class.visible]="listLoaded" (tap)="seeItem($event)" swipeActions="true" (itemSwipeProgr ...

How can you make sure that a class property in TypeScript always matches the name of the class?

Click here for an example interface ICommandHandler<T> { type: string // how can we ensure that this equals T.name? handle(command: T): void; } interface ICommand {} class CreateTaskCommand implements ICommand{} class CreateTaskCommandHandler ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Exploring TypeScript's Classes and Generics

class Person { constructor(public name: string) {} } class Manager extends Person {} class Admin extends Person {} class School { constructor(public name: string) {} } function doOperation<T extends Person>(person: T): T { return person; } ...

Unspecified parameter for Next.js dynamic route

Currently, I am developing an e-commerce application using next.js with Typescript and MongoDB. To better understand my project, let's take a look at my existing file structure: https://i.stack.imgur.com/tZqVm.png The mainPage.tsx file is responsibl ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

Prevent the Mat Dialog from showing up depending on the situation

I am attempting to prevent a Mat Dialog from appearing unless a specific condition is met. I originally thought about using Angular Guard, but since there is no associated route with the component (besides the main webpage it's called from), that appr ...

Looking to update the state of a nested object with useReducer?

I am currently developing a Next.js application using Typescript and I need to make changes to a nested object state. Here is the structure of the state: const initialState ={ userInfo: string | null, isLoading: boolean, cursorState: boolean, compa ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

How can I ensure a module in Angular module federation v14 is only loaded in either the parent or child app, but not both?

I am currently utilizing Angular 14 along with module federation in my project. Within my child application, I have the following configuration: module.exports = withModuleFederationPlugin({ name: 'childapp', exposes: { './app1&apos ...

ArrangementGrid utilizing ngFor directive for rows and columns

Hi there, I am new to using Nativescript and I have encountered an issue with ngFor. Specifically, I am working with a GridLayout that contains a StackLayout inside of it and I need to set dynamic col and row values within the StackLayout. Can anyone pro ...

Displaying a facebox modal window following an asynchronous request

Within the head tags of my HTML page, I have included the necessary code to load the Facebox plugin: <!-- Code for the Facebox plugin setup --> <link href="<?php echo base_url();?>styles/facebox/src/facebox.css" media="screen" rel="styleshe ...