Angular 2: Using ngModel to bind radio inputs with boolean values

How can I bind 2 radio button input options in Angular 2 to a boolean model property without encountering binding issues?

*.component.html:

Issue: Unable to select one of the radio buttons, always getting false for myModel.modelProperty.

<div class="form-group">
        <label for="modelProperty">Model Property: </label>
        <form action="">
            <input type="radio" [ngModel]="_model.modelProperty"  (click)="_model.modelProperty=true" name="modelProperty" value=true>Yes<br>
            <input type="radio" [ngModel]="_model.modelProperty"  (click)="_model.modelProperty=false"  name="modelProperty" value=false>No
         </form>
</div> 

<div>{{_model.modelProperty}}</div>

*.component.html:

Issue: Getting [Object object] for myModel.modelProperty, only able to select No radio button.

<div class="form-group">
            <label for="modelProperty">Model Property: </label>
            <form action="">
                <input type="radio" [(ngModel)]="_model.modelProperty"   name="modelProperty" ngValue=true>Yes<br>
                <input type="radio" [(ngModel)]="_model.modelProperty"   name="modelProperty" ngValue=false>No
             </form>
    </div> 

    <div>{{_model.modelProperty}}</div>

Using the following:

*.component.ts for all *.component.html options above:

import {Component, Input} from 'angular2/core';
import {NgForm}    from 'angular2/common';
import {Model}    from './model';
@Component({
  selector: 'my-form',
  templateUrl: 'app/.../*.component.html'
})

export class *Component {

      _model = new Model(..., false, ...); //false is the Model property: .modelProperty

      constructor(){}

      ...
}

Answer №1

If you want your HTML value to be interpreted as a boolean, you can achieve this by setting: [value]="true"

Answer №2

When facing similar situations, I often utilize the initial version of the code which involves [checked] rather than [ngModel].

The following code has proven to be effective for me:

<form action="">
    <input type="radio" [checked]="_model.modelProperty" 
        (click)="setProperty($event.target.checked)"
        name="modelProperty">Yes<br>
    <input type="radio" [checked]="!_model.modelProperty" 
        (click)="setProperty(!$event.target.checked)" 
        name="modelProperty">No 
</form> 

setProperty(inChecked: boolean) { 
    this._model.modelProperty = inChecked; 
}

Answer №3

When dealing with boolean values, [(ngModel)] can be used in conjunction with [value]. However, it should be noted that [(ngModel)] does not automatically check the checkbox or radio button with the specified value.

<input type="radio" 
   id="idYes" 
   name="Preferred-group" 
   [value]="true" 
   [(ngModel)]="IsContactPreffered"> 

This code snippet works as expected without any issues.

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 Twitter Bootstrap 3 and 2 alongside Angular 2 for web development

Our current Main application is developed using Angular 1.4 and incorporates Twitter Bootstrap 2.3.2. This application includes various components built with Angular 1.4 by different teams, We are now looking to create new components using Angular 2, and ...

Tips for dynamically incorporating filtered selections into a Mat-Select dropdown

I am seeking guidance on how to prevent changing the values of already selected values in other rows when each row of the formArray is altered. Adding controls dynamically and correctly retrieving values in filters are functioning properly. The issue arise ...

Unable to load custom package in Angular 2 testing environment

I've been following the official Angular 2 testing guide on an existing project. Everything runs smoothly when I use my custom library, downloadjs, in the application. However, I encounter an error in the console during test execution: "__zone_symbol ...

Publish an Angular application's production version using Zeit Now

I've been utilizing zeit now for deploying an Angular application. The steps I followed can be found in this guide. The Angular app was created using the Angular CLI and was developed locally using the command ng serve. Deployment was done by executi ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

Creating a TypeScript mixin with a partial class is a useful technique that allows you to

I am attempting to have class A inherit properties from class B without using the extends keyword. To achieve this, I am utilizing a mixin in the following manner: class A{ someProp: String someMethod(){} } class B implements classA{ someProp: String ...

Distinguish between two varieties using parameters

Let's consider the following simplified example: type Reference<T extends {identifier: string}> = T['identifier'] In this type, TypeScript recognizes that it is a reference to an object where the identifier property is of type string ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...

What causes the act of clicking a button to alter a particular section of my vscode extension to seem so detrimental?

Background Language used : typescript UI toolkit svelte and bootstrap Description of Problem I am currently developing a vscode extension where clicking a button should update an HTML table element in the view based on the button clicked. Here is the type ...

Combining observables from two tables in angularfire2 using rxjs with dynamic updates

I am faced with the challenge of merging two tables: one for storing user blocks and the other for storing data related to these blocks. My goal is to successfully combine these in a way that allows me to retrieve a list of blocks along with their corresp ...

Adding Dynamic Controls in Angular 4: A Guide

For this illustration, I've put together a compact form that allows me to introduce dynamic controls by simply clicking on the "Add Pre-Phase" button. Once a few pre-phases are added, I will designate a phase type, and if the chosen value is EMS, the ...

How to efficiently filter an array containing nested objects using TypeScript

I'm currently working with a list of menus and submenus: [ { "NUA_ID_Menu": 1, "TXT_Nom_Menu": "Menu 1", "Liste_Sous_Menus": [ { "TXT_Nom_Menu": ...

Having trouble loading CSS with the Minimal Webpack 2 setup for BlueprintJS

My goal is to establish a basic webpack 2 configuration for testing BlueprintJS and TypeScript. I believe I'm on the right track, but the CSS isn't loading properly. Below is the project's directory structure: src/ index.tsx App.tsx App ...

Unable to Sort Angular Material Data Table

Struggling to organize my data as the sorting functionality is not behaving as expected. Unlike the typical examples that use a local array of values, my situation involves an API call that returns an array of objects, with each object containing a 'n ...

Unable to integrate moment.js or ng2-bootstrap into my Angular 2 project

While running my gulp tslint task, I encountered an error message. It seems that I need to add moment.js in order to satisfy ng2-bootstrap. In node_modules/ng2-bootstrap/components/datepicker/date-formatter.ts(1,25), I received the following error: &apo ...

The 'Key' identifier is not valid for indexing the 'Object' data type

Currently attempting to incorporate functional pluck with a specific sound type, but encountering an issue: function extract<Object extends {}, Key = keyof Object>(key: Key): (o: Object) => Object[Key] { return object => object[key]; } Erro ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Issue with Webpack Build Excluding JSON Resource Files

My Webpack build is not including the resources folder in the dist build, resulting in the translation files not being picked up and causing the translations to not take place... File structure: dist //The json files from src/resources need to be incl ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...