Utilize a single component across various instances for enhanced efficiency

After thorough research, I couldn't find a solution to my problem despite similar questions being asked.

I've developed an angular component for styled radio buttons and need to use it multiple times on different instances.

To get a better understanding, please refer to this image:

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

How can I achieve independent behavior for multiple instances?

A summary of the relevant parts in my code:

Parent component .ts file:

    import { Component, ElementRef, ViewChild, AfterViewInit  } from '@angular/core';
    import { TxtZoneComponent } from './txtzone/txtzone.component';
    import { EditorDirective } from './txtzone/editor.directive';
    import { RadioButtonComponent } from './CustomControls/RadioButton';

    @Component({
        selector: 'my-app',
        templateUrl: 'app/app.component.html',
        styleUrls: ['app/App.css'],

    })
    export class AppComponent {
        public Myheader: string = "Line Breaker Web Application"
        public RadButtonBackColor: string = "rgb(50,50,50)"
        @ViewChild(EditorDirective) vc: EditorDirective;
        constructor()
        {

        }

}

Parent component .html file:

<div><MyRadBtn [Description]="'Break Word'" [BackColor]="RadButtonBackColor">Loading...</MyRadBtn></div>
<div><MyRadBtn [Description]="'SQL Mode'" [BackColor]="RadButtonBackColor">Loading...</MyRadBtn></div>

RadioButton component .ts file:

import { Component, Input, OnChanges, NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
    selector: 'MyRadBtn',
    templateUrl: 'app/CustomControls/RadioButton.html',
    styleUrls: ['app/CustomControls/RadioButtonStyleSheet.css'],
})

export class RadioButtonComponent
{


    @Input() BackColor: string = "rgb(50,50,50)";
    @Input() Description: string;
    constructor()
    {

    }

    ngOnChanges() {

    }

    clicked(): void
    {
        alert(this.Description);
    }
}

RadioButton .html file:

<div class="breakwordcont" [ngStyle]="{'background-color': BackColor}">
    <div class="desc"><span>{{Description}}</span></div>
    <div class="control">
        <div class="slideOne">
            <input type='checkbox' value='None' id='slideOne' name='check' (click)="clicked()" />
            <label for="slideOne"></label>
        </div>
    </div>
    </div>

RadioButton .css file:

input[type=checkbox] {
    visibility: hidden;
}

.slideOne {
    width: 50px;
    height: 10px;
    background: #333;
    margin: 5px auto;

    -webkit-border-radius: 50px;
    -moz-border-radius: 50px;
    border-radius: 50px;
    position: relative;

    -webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
    -moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
    box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
}

.slideOne label {
    display: block;
    width: 16px;
    height: 16px;

    -webkit-border-radius: 50px;
    -moz-border-radius: 50px;
    border-radius: 50px;
    
     /* Remaining CSS styles */
 
 

EDIT FOR FUTURE VIEWERS WITH THE SAME ISSUE


based on @deek answer, here are the relevant changes in my fixed code:

1. adding ID property to radioButton .ts file:

export class RadioButtonComponent
{
    @Input() ID: string;
// ... rest of class definitions...
}
  1. Passing the ID for each radio button from the parent component:

      <div><MyRadBtn [ID]="'id-one'" [Description]="'Break Word'" [BackColor]="RadButtonBackColor">Loading...</MyRadBtn></div>
      <div><MyRadBtn [ID]="'id-two'" [Description]="'SQL Mode'"  [BackColor]="RadButtonBackColor">Loading...</MyRadBtn></div>
    
  2. binding the id of the input to the css class:

     <div class="breakwordcont" [ngStyle]="{'background-color': BackColor}">
         <div class="desc"><span>{{Description}}</span></div>
         <div class="control">
             <div class="slideOne">
                 <input type='checkbox' value='None' id={{ID}} name='check' />
                 <label for={{ID}} (click)="clicked()"></label>
             </div>
         </div>
     </div>
    

Answer №1

UPDATE: input[type=checkbox]:checked + label

only implement this rule if the passed ID matches the clicked element.

The issue lies in the class and ID names of the input in the Radio component.

Upon injection, both the code has them with the same ID and class names.

You have two options - either create separate components with different CSS/IDs or take an input parameter to set the class name and id based on the desired css. The latter is recommended.

You can simply assign a different ID depending on your css (assuming you haven't read it all).

<div><MyRadBtn [slideClass-ID]="id-one" [Description]="'Break Word'" [BackColor]="RadButtonBackColor">Loading...</MyRadBtn></div>
<div><MyRadBtn [slideClass-ID]="id-two" [Description]="'SQL Mode'" [BackColor]="RadButtonBackColor">Loading...</MyRadBtn></div>

Then bind the id for the input to slideClass-ID.

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

Leveraging angular-cli built files as a dependency for another angular2 project

Is it feasible to utilize the build artifacts from one angular-cli project in another? For instance, I have created and published project "A", then subsequently created project "B" and added A to its dependencies (node_modules). Currently, these are the ...

"Utilizing the `useState` function within a `Pressable

Experiencing some unusual behavior that I can't quite figure out. I have a basic form with a submit button, and as I type into the input boxes, I can see the state updating correctly. However, when I click the button, it seems to come out as reset. Th ...

The specified type '{ data: any; }' is incompatible with the type 'IntrinsicAttributes'. The property 'data' is not found in the type 'IntrinsicAttributes'

I'm encountering issues with the data property. interface Props { params: { slug: string }; } const Page = async ({ params }: Props) => { const data: any = await getPage(params.slug); // This section dynamically renders the appropriate orga ...

How to update an array in Angular using ngModel and ngFor

I am attempting to display an array's values on a form and then allow for updating those same values in the array (using name="todos{{i}}" within the <input> tag does not work as it turns it into a string instead of an array). The curr ...

Is there a way to reverse the color scheme on ngx-charts-heat-map?

I have been successfully using the ngx-charts-heat-map to generate a heat map. Everything seems to be working fine, but I am facing a small issue that I can't seem to figure out. Currently, the color of each cell on the map corresponds to its value ...

Filtering an array of objects in TypeScript based on the existence of a specific property

I'm attempting to filter objects based on whether or not they have a specific property. For example: objectArray = [{a: "", b: ""}, {a: ""}] objectArray.filter( obj => "b" in obj ).forEach(obj => console. ...

Attempting to utilize pdf.js may result in an error specifying that pdf.getPage is not a recognized function

After installing pdfjs-dist, I attempted to extract all text from a specific PDF file using Node and pdfjs. Here is the code I used: import pdfjs from 'pdfjs-dist/build/pdf.js'; import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry.js&a ...

What is the best way to send a search parameter to a URL?

In my asp.net core web api, I developed a method that generates an object with the string provided in the URL. I now have a search form that needs to pass this string to the URL and retrieve the objects containing it. Here is how I utilize the api: impo ...

Generate a new data type based on the value of a single attribute within a collection of objects

Is there a way to extract a specific property of a combined type and generate a new type from it? Consider the following example: type Actions = | { type: "ADD_COLUMN"; newColumnIndex: number; column: SelectorColumnData; } | { type: ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

Deriving data types based on a variable in TypeScript

If I have a dictionary that links component names to their corresponding components like this: const FC1 = ({prop}: {prop: number}) => <>{prop}</>; const FC2 = ({prop}: {prop: string}) => <>{prop}</>; const mapComponents = [ ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

ERROR: The request for URL /Angular2 resulted in an HTTP status of 404, indicating that the resource could

Trying to receive an http response within my service: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class CartService { ...

Issue with Angular 2 in Visual Studio 2013: Pressing Ctrl+K+D causes formatting to change to lowercase

Please note that while this issue is not directly related to Angular2, anyone who uses Angular2 with Visual Studio 2013 may be able to help. Whenever I use the key combination Ctrl + K + D in Visual Studio 2013, it changes HTML or Angular2 directives/mark ...

Unable to close keyboard on Ionic 5 app for both Android and iOS platforms

Hello there, I'm currently facing an issue trying to hide/dismiss the keyboard on both iOS and Android devices while using the Ionic 5 platform with Angular. I've attempted various methods such as keydown.enter, keyup.enter, and keypress without ...

Using Bootstrap 4 with Angular 2: A Beginner's Guide

Currently, I am in the process of developing an Angular 2 application using TypeScript. My goal is to integrate the Bootstrap 4 framework with some custom theming. Is this achievable? I have encountered issues with the "ng2-bootstrap" npm package, as it d ...

The type of link component that is passed in as the 'component' prop

I have created a custom Button Function Component in TypeScript using Material-UI as the base. After styling and adding features, I exported it as my own Button. Now, when I try to use this Button component in conjunction with the Link component from react ...

Angular Bootstrap Datepicker provides us with a date object, but I need it in the Date format

My desired date format is "Wed Aug 07 2019 16:42:07 GMT+0530 (India Standard Time)", but instead I am receiving { year: 1789, month: 7, day: 14 } from ngbDatepicker. Any assistance on resolving this issue would be greatly appreciated. ...

The console.log method is not functioning properly in the service

When developing my Angular application, I encountered an issue while creating a service. Here is the code snippet: @Injectable({ providedIn: 'root' }) export class PropertiesNameService { properties: string[] = []; constructor(p ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...