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

Angular: Attempting to coordinate communication between two functions within my service

I have two separate functions but I would like them to sync up and work together. The first function is called getRandomNumbers - its role is to display a random number between 1 and 20 every second. The second function is up - it's a button that al ...

Removing feedback on a particular blog entry

I'm struggling to remove all comments associated with a specific blog post that is about to be deleted using mongoose. I can't figure out why my code isn't functioning correctly. const commentSchema = new mongoose.Schema({ message: { type ...

FIREBASE_AUTHCHECK_DEBUG: Error - 'self' is undefined in the debug reference

I'm encountering an issue while trying to implement Firebase Appcheck in my Next.js Typescript project. firebase.ts const fbapp = initializeApp(firebaseConfig); if (process.env.NODE_ENV === "development") { // @ts-ignore self.FIREBASE_ ...

When subscribing to an Observable of type number or string (union type), NaN values are returned for string inputs

Within a component, I have a public member that is defined as follows: public docId$: Observable<number | string>; This means that the document ID can either be an integer or a string. Upon initializing in ngOnInit, I have the following code snippe ...

Retrieving Data in Typescript Async Function: Ensuring Data is Returned Once All Code is Executed

I need help with waiting for data to be retrieved before returning it. The code below fetches data from indexedDB and sends it back to a component. I understand that observables or promises can accomplish this, but I am struggling with how to implement t ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...

I am experiencing difficulty with VS Code IntelliSense as it is not displaying certain classes for auto-import in my TypeScript project

I'm currently working on a project that has an entrypoint index.ts in the main folder, with all other files located in src (which are then built in dist). However, I've noticed that when I try to use autocomplete or quick fix to import existing ...

Angular 2 encountering a memory exhaustion issue in the JavaScript heap

I am currently using Angular CLI and would appreciate it if you could verify my CLI information @angular/cli: 1.2.1 node: 6.10.0 os: win32 x64 @angular/animations: 4.1.1 @angular/common: 4.0.0 @angular/compiler: 4.0.0 @angular/compiler-cli: 4.0.0 @angular ...

Preventing angular mat-menu from closing when clicking outside of it: simple solutions

When implementing MatMenu as a popup for guiding new users on my web app, I prefer not to close it when the user clicks outside of it. I've successfully used $event.stopPropagation() to prevent closure when clicking a button within it. Now, I'm ...

When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string. Here is what I aim to achieve with my output: "This is an example!" ==> "sihT ...

What are some ways to optimize the performance of a Select Box?

I am attempting to show a lengthy list of countries in an ion-select. Currently, there are 249 countries that I need to load. Unfortunately, the rendering performance is quite slow on my phone. <ion-list margin-top margin-bottom> <ion-item> ...

Having trouble determining whether a modal is currently open in an Angular application?

Greetings! I am currently working on a web application using Angular. Below is the code I have for opening a modal popup: this.formResetToggle = false; setTimeout(() => { this.formResetToggle = true; this.editorModal.s ...

Angular application unable to invoke the Web API GET method

Just starting out with Angular. I've got a WebAPI controller set up with a get method that returns data. Everything runs smoothly when I access it from the browser directly. But for some reason, when I try to call the same method from my Angular ap ...

Utilize the useTheme type from Emotion Js within ReactJs using Typescript

Greetings! As a newcomer to typescript, I find myself with a query regarding the use of Theme in emotionJs. Here's the snippet of code that has been causing me some trouble: const GlobalStyle: React.FC = (props) => { const Theme = useTheme(); ...

What's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

Angular displays error ERR_UNKNOWN_URL_SCHEME when attempting to retrieve an image saved in a blob

As I transition my app from Electron to Angular, one of my main objectives is to display an image uploaded by a user. Here's how I attempted to achieve this: page.component.ts uploadImageFile(){ fileDialog({}, files =>{ //Utilizing the fileDi ...

What is the best way to transfer a value from a parent component to a directive within Angular 2?

In the parent component, I currently have this line of code: <input datepicker type="text" (change)="update($event)"/> Is there a way for me to provide a value to the datepicker directive? ...

Passing a variable to a cloned template in Angular 2: A guide

When working with Angular2, I encountered an issue with my template code that I am cloning every time a user clicks a button. Despite following instructions provided in this post How to dynamically add a cloned node in angular2 (equivalent to cloneNode), I ...

Initiating the ngOnInit lifecycle hook in child components within Angular

I am facing an issue with controlling the behavior of child components in my Angular application. The problem arises when switching between different labels, causing the ngOnInit lifecycle hook of the children components not to trigger. The main component ...