Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular.

Below is the code snippet for the markup I want to make functional within the parent component:

<form>
  <my-radio [(ngModel)]="radioBoundProperty" value="1" name="myCustomRadioButton">Btn 1</my-radio><br>
  <my-radio [(ngModel)]="radioBoundProperty" value="2" name="myCustomRadioButton">Btn 1</my-radio><br>
</form>

<p>
  The current value of radioBoundProperty is:
</p>
<pre>{{radioBoundProperty|json}}</pre>

So far, I have created a custom radio component by utilizing ControlValueAccessor.

The issue arises when attempting to retrieve the selected value from my-radio component back to the parent component using ngModel for two-way data binding.

Even if I modify the value of radioBoundProperty, it overrides the values of the `value` attribute for both my-radio elements.

Click here for an updated stackblitz that demonstrates a successful example:

stackblitz showcases the functioning example with accompanying code

Answer №1

Utilize the registerOnChange function to transmit the value to the parent component.

export class RadioModel implements ControlValueAccessor { 
    onChange = (val: string) => { };
    onTouched = () => { };
    onApplied = () => { };

    writeValue(val: string): void {
        // Handle changes with the writeValue function
    }

    registerOnChange(fn: (val: string) => void): void {
        this.onChange = fn;
    }

    registerOnTouched(fn: () => void): void {
        this.onTouched = fn;
    }

    valueChanged(){
         this.onChange('your value');
    }
}

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

Utilizing NodeJS application to connect to Sharepoint 2019 On-Premises Web Services

Recently, I/T in my organization set up a new Sharepoint 2019 OnPromise with a hybrid configuration that utilizes Azure AD for authentication. As the site collection admin for our Sharepoint website, the URL to access it is Upon accessing this URL, I am ...

How to save data to a JSON file using the filesystem module in Node.js

After coming across this helpful guide at , I was intrigued by the creation of a point system in discord.js. The use of let points = JSON.parse(fs.readFileSync("./points.json", "utf8")); to read the file piqued my interest, leading me to explore how to bui ...

Exploring the power of JavaScript Callback using nano and now.js

every.person.now.guessValue = function(value) { database.find('lists', 'project_names', { startingPoint: value, endingPoint: value + "\u9999" }, function(_, information) { return information.rows.map(function( ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

What is the best way to simultaneously check two conditions in Vue.js?

In my current scenario, I am facing a challenge with checking both conditions simultaneously. If an attachment exists in the request but the attachment field does not exist in the form, it should display a message in the modal. Similarly, if body text exis ...

Ordering an array in Angular 2: A step-by-step guide

I am working on an Ionic 2 app with an older version of AngularJS that does not have the orderby pipe by default. As a result, I have an array structured like this: <div *ngFor="let boatBooking of boatBookings" style="padding: 0px; margin:0px;"> ...

Utilizing Vue and TypeScript - Retrieving a Variable Declared in the Data() Method within Another Method

I recently made the switch to using Vue3 with TypeScript after previously working with Vue2 and JavaScript. I am encountering an issue in my IDE where it is showing an error (even though the code itself functions correctly, but may not be entirely accurate ...

Using Angular 2, perform an HTTP GET request to retrieve data from a JSON file located in the assets folder

Currently, I am working on fetching data from a JSON file located in the assets folder of my application. The framework I am using is Angular Material. For this purpose, I have created an account component which consists of the following files: account.co ...

`Firebase User Instance and Custom Firestore Document`

Recently, I posted a question regarding Google Firebase Angular Firestore switchMap and encountered some issues. The question can be found here. After exploring AngularFireAuth, I learned that it is used to create a User object with fixed values, requirin ...

Update the contents of a div element with JavaScript and PHP combo

When I click on the following div, I want to replace it with a similar one from file.php. The div tag in question is: <div style="display: none;" id="extra" class="container2" xml:id="page"> <div class="title"> <h2>Stuff to check out< ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

How can you implement WriteFile in a GET Request without causing the response to be blocked

During the initialization of the app, I require a specific request to be made. This request entails parsing a portion of the JSON response into JavaScript and then saving it to a file. Simultaneously, the rest of the response needs to be sent to the front ...

Discovering the URL of an AJAX request on any given website

Is there a way to retrieve the URLs of AJAX requests that are sent by the current page on a website using a browser or another tool? ...

Modules that are imported in the AppModule will not be accessible in other modules

Suppose this represents my AppModule: @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, MaterialModule, HomeModule ], exports: [ MaterialModule ], providers: [], bootstrap: [App ...

What could be causing json_decode to return NULL in this scenario?

I have a custom array that I've created with the following structure: [{ "assetPreviewUrl":"pic1.jpg", "assetUrl":"pic2.jpg" }, { "assetPreviewUrl":"pic3.jpg", "assetUrl":"pic4.jpg" }] My approach involves stringifying this array and ...

The Angular Material Datepicker lacks any selected date

I am currently in the process of developing a web application using Angular and incorporating Angular Material for certain UI components. I have encountered an issue that I am unable to resolve. When attempting to use the datepicker as outlined on https:// ...

The postMessage function in my Javascript SlackBot seems to be flooding the channel with messages

I am currently setting up a Slack bot using JavaScript combined with several useful libraries. The main function of this bot is to execute a postMessageToChannel method whenever a user in the channel mentions the specific keyword "help." However, I am fa ...

Tips for handling a promise that has not been fulfilled

Is there a way to return a promise and trigger its failure block right away? Check out this unconventional method: if (fail) { var q = $q.deferred(); $timeout(function() { q.reject("") }, 1); return q.promise; } else { return ...

Tips for showcasing styled text in Vue using API data

I'm having trouble formatting text in Vue. Within a component, I have a textarea that stores a string with backspaces, etc ... in an API like this: A cellar but not only...\n\nWelcome to the Nature & Wine cellar, a true Ali-baba's cave ...