Polls in Ionic
- Fire Focus
- Oct 1, 2020
- 2 min read
Updated: Oct 2, 2020
Introduction
In this lesson,I will teach you how you can create a simple logic without any backend integration Polling System in Ionic.
Note: This is a logic only polling system ie., I show you how you can create a polling in your app or website with this logic
Output

The Code
Here, I have an array that contains the polls called polls that includes question,total number of votes,options with choices and total number of votes for each choice.
There is a variable called alreadyVoted that will be used to show the ion-progress-bar and percentage text once a choice is clicked.
poll.page.ts
alreadyVoted = false;
polls: Array<any> = [
{
question: "Which is better option to make mobile apps?",
totalVotes: 0,
options: [
{
choice: "Ionic",
votes: 0,
color: "primary"
},
{
choice: "Flutter",
votes: 0,
color: "success"
},
{
choice: "React Native",
votes: 0,
color: "warning"
},
{
choice: "Framework 7",
votes: 0,
color: "danger"
}
]
}
];
Here, we have 3 functions polling(),getValue(),getPercent().
polling(i,j) - This function is to vote for a choice.The parameters i and j takes the index of the poll in array and index of choice inside the poll respectively.On triggering this function we increment the totalVotes and votes of the choice clicked.
getValue(votes, totalVotes) - This function returns the value for the ion-progress-bar for each choice by dividing the votes by totalVotes.
getPercent(votes, totalVotes) - This function returns the total percentage for each choice.
poll.page.ts
polling(i, j) {
this.alreadyVoted = true;
this.polls[i]['options'][j]['votes'] = this.polls[i]['options'][j]
['votes'] + 1;
this.polls[i]['totalVotes'] = this.polls[i]['totalVotes'] + 1;
}
getValue(votes, totalVotes) {
let value = votes / totalVotes;
return value;
}
getPercent(votes, totalVotes) {
let value = (votes / totalVotes) * 100;
return Math.round(value) + "%";
}
The Markup
Here, we have simple markup with ion-card that iterates over using ngFor.
There is a click event on each choice.
poll.page.html
<ion-card mode="ios" *ngFor="let poll of polls;let i=index">
<ion-card-header>
<ion-card-title>{{poll.question}}</ion-card-title>
<ion-card-subtitle>{{poll.totalVotes}} votes</ion-card-subtitle>
</ion-card-header>
<ion-card-content>
<ion-radio-group>
<ion-item *ngFor="let option of poll.options;let j=index" (click)="polling(i,j)">
<ion-radio slot="start" color="{{option.color}}"></ion-radio>
<ion-label>{{option.choice}}
<ion-progress-bar value="{{getValue(option.votes,poll.totalVotes)}}" color="{{option.color}}" *ngIf="alreadyVoted"></ion-progress-bar>
</ion-label>
<ion-note *ngIf="alreadyVoted">{{getPercent(option.votes,poll.totalVotes)}}</ion-note>
</ion-item>
</ion-radio-group>
</ion-card-content>
</ion-card>
I hope you understand the lesson.Please leave your feedback in comments.Cheers!
Comentários