DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • AngularJS Vs. ReactJS Vs. VueJS: A Detailed Comparison
  • 50+ Top Angular Interview Questions and Answers
  • Rediscovering Angular: Modern Advantages and Technical Stack

Trending

  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Unlocking AI Coding Assistants Part 3: Generating Diagrams, Open API Specs, And Test Data
  1. DZone
  2. Data Engineering
  3. Data
  4. Data Bind Radio Button Lists With Angular 2

Data Bind Radio Button Lists With Angular 2

We need to establish some data binding between our data and the radio buttons. Let's see how to do that with Angular 2.

By 
Juri Strumpflohner user avatar
Juri Strumpflohner
·
Nov. 28, 16 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
88.7K Views

Join the DZone community and get the full member experience.

Join For Free

Assume you have a simple list or table of elements, each row having a radio button. The user can select one of the rows and your task is to determine the selected row entry. We basically need to establish some data binding between our data and the radio buttons. Let's see how to do that with Angular 2.

First of all, assume this is our data structure:

[
    {
        id: 1,
        description: 'entry 1'
    },
    {
        id: 2,
        description: 'entry 2'
    },
    ...
]

For the purpose of not complicating our example more than needed, we create a simple HTML table inside our component, and iterate over the <tr> elements using *ngFor.

@Component({
    ...
    template: `
      <table>
        <thead>
          <td>Description</td>           <td></td>         </thead>         <tbody>
          <tr *ngFor="let entry of entries">
            <td>{{ entry.description }}</td>             <td>
                <input type="radio" name="radiogroup">
            </td>           </tr>         </tbody>       </table>     `
})
export class App { 
    entries = []
}

Pre-Select the First Radio Button of the List

Given that we specified the name="radiogroup" on our radio button, always only one radio button can be selected in our list. This is plain standard HTML behavior. Therefore, it’s good practice to preselect the first one. How do we determine the 1st row within our *ngFor loop? We use the index property. Once we have that we can conditionally add the checked property to our radio button based on whether the current index in our iteration is equal to 0.

<tr *ngFor="let entry of entries; let idx = index">
    <td>{{ entry.description }}</td>
    <td>
        <input type="radio" name="radiogroup" [checked]="idx === 0">
    </td>
</tr>

Binding: Model -> Template

The important part is our <input type="radio"...> here, so let’s take a closer look. First of all we want to bind in the value which is determined by the id property of our entry data object. We can bind the value using the [ ] brackets.

<tr *ngFor="let entry of entries">
    <td>{{ entry.description }}</td>
    <td>
        <input type="radio" name="radiogroup" 
            [checked]="idx === 0" 
            [value]="entry.id">
    </td>
</tr>

Binding: Template -> Model

Great, so now that we’ve databound our model to our template by using the [value] attribute on our radio button list, we need however to also bind the currently selected radio button back to our component. This is important in order to understand which radio button the user ultimately selected. Our strategy here is to bind to the native “change” event on our radio button element. In Angular we can simply do this by using the ( ) brackets.

<tr *ngFor="let entry of entries">
    <td>{{ entry.description }}</td>
    <td>
        <input type="radio" name="radiogroup" 
            [checked]="idx === 0" 
            [value]="entry.id" 
            (change)="onSelectionChange(entry)">
    </td>
</tr>

Obviously, the onSelectionChange(...) function needs to be defined on our component, so let’s do that. The implementation is actually quite simple, we only go and remember our currently selected entry on a component level variable.

@Component({...})
class App {
    entries = [];
    selectedEntry;

    onSelectionChange(entry) {
        this.selectedEntry = entry;
    }
}

We could even go a step further and create a copy of our object, which is good practice to provide object immutability. In combination with OnPush change detection strategy, this can make quite some performance difference. But that’s the story of another blog post.

@Component({...})
class App {
    ...
    onSelectionChange(entry) {
        this.selectedEntry = Object.assign({}, this.selectedEntry, entry);
    }
}

Final Code

Here’s the final code in an easy to use Plunk:

<!DOCTYPE html>
<html>

  <head>
    <base href="." />
    <title>angular2 playground</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>

  <body>
    <my-app>
    loading...
  </my-app>
  </body>

</html>

Conclusion

As you can see, we use a clean one-way data flow approach when binding to our radio button. We use input bindings with [value] and output bindings with events, namely the native radiobutton’s (change) event.


If you enjoyed this article and want to learn more about Angular, check out our compendium of tutorials and articles from JS to 8.

Data binding AngularJS

Published at DZone with permission of Juri Strumpflohner. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • AngularJS Vs. ReactJS Vs. VueJS: A Detailed Comparison
  • 50+ Top Angular Interview Questions and Answers
  • Rediscovering Angular: Modern Advantages and Technical Stack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!