How to get multiple radio buttons to work in angular2? - html

I have a array of json, something similar to this:
questions =
[
{
title: Your section is?
choices: [
{
id: 1,
label: "TestA"
},
{
id=2,
label: "TestB"
}
]
},
{
title: Your major is?
choices: [
{
id=3,
label: "Medicine"
},
{
id=4,
label: "Engineering"
}
]
}
]
My html:
<div *ngFor="let choice of questions">
<div *ngFor="let choice of questions.choices;let i=index">
<div class="radio-group" (click)="onSelectChoice(choice.id)">
<input type="radio" class="hide" name="choiceElements" [value]="choice.id" id="choice.label" formControlName="choiceElements">
<label [class.selected]="choice.id === selctedRadio" for="{{choice.label}}" class="" >{{choice.label}}</label>
</div>
</div>
</div>
My TS:
selctedRadio: '';
onSelectChoice(selctedChoice: any){
this.selctedRadio = selctedChoice;
}
So, in html I need two questions, each question having two buttons, for each question I should be able to select one radio button.
But in my case, I am able to select only one radio button and when I go to second question the selected first question becomes unselected.
Let me know how I can be able to select one radio answer from each question.

Your radio buttons must have the same name if and only if they belong to the same group.
You will have to find a way to create a unique-per-group name.
By the way, this is not angular specific, it's just how radio buttons work in plain HTML.
however, for more info about how to handle radio buttons in angular, you can check this :
Angular2 ReactiveFormsControl: how to bind radio buttons?
Angular2 - Radio Button Binding

Related

Angular Checkbox - Cannot get the value of database to match the checkmarks in html checkbox

Looking for your kind assistance as I am still new to coding and angular.
I have this form which allows to me do CRUD data.
In adding the data, I have a several checkbox which I can manage to successfully stored in the database.
However, when I am trying to edit the data, the checkbox are no longer showing check markings based on the data in the table.
I have a Modal form and I am having a hard time matching the data in the checkbox to the ones in database.
Component.html
<div>
<div *ngFor="let item of _placarddetails">
<input type="checkbox" name="{{item.id}}" [(ngModel)]="item.isselected">
<label> {{item.name}}</label>
</div>
</div>
Component.TS
ngOnInit(): void {
this.loadPlacardQualityList();
}
loadPlacardQualityList(){
this.service.getAllEdcmTicketNo().subscribe((data:any)=>{
this.PlacardQualityList=data;
this.PlacardQualityId=this.pq.PlacardQualityId;
this.EdcmTicketNo=this.pq.EdcmTicketNo;
this.PQDeliveryDate=this.pq.PQDeliveryDate;
this.PlacardAppearance=this.pq.PlacardAppearance;
this.PlacardDetails=this.pq.PlacardDetails ;
this.PlacardAcceptance=this.pq.PlacardAcceptance;
this.Inserts=this.pq.Inserts;
this.CheckedBy=this.pq.CheckedBy;
this.PowerProduct=this.pq.PowerProduct;
this.Comment=this.pq.Comment;});
this.
}
addPlacardQuality()
{
var val = {
PlacardQualityId:this.PlacardQualityId,
EdcmTicketNo:this.EdcmTicketNo,
PQDeliveryDate:this.PQDeliveryDate,
PlacardAppearance:this.PlacardAppearance,
PlacardDetails:this.PlacardDetails = this._placarddetails.filter(x=>x.isselected==true).map(x=>x.name).join(","),
PlacardDetailsID:this.PlacardDetails = this._placarddetails.filter(x=>x.isselected==true).map(x=>x.name).join(","),
Inserts:this.Inserts,
CheckedBy:this.CheckedBy,
PowerProduct:this.PowerProduct,
Comment:this.Comment};
this.service.addPlacardQuality(val).subscribe(res=>{alert(res.toString());
});
}
updatePlacardQuality(){
var val = {
PlacardQualityId:this.PlacardQualityId,
EdcmTicketNo:this.EdcmTicketNo,
PQDeliveryDate:this.PQDeliveryDate,
PlacardAppearance:this.PlacardAppearance,
PlacardDetails:this.PlacardDetails = this._placarddetails.filter(x=>x.isselected==true).map(x=>x.name).join(","),
Inserts:this.Inserts,
CheckedBy:this.CheckedBy,
PowerProduct:this.PowerProduct,
Comment:this.Comment}
this.service.updatePlacardQuality(val).subscribe(res=>{alert(res.toString());});
}
getPlacardDetails()
{
this._placarddetails=[
{id:1,name:"Company Name",isselected:false},
{id:2,name:"Company Logo",isselected:false},
{id:3,name:"Certification Level",isselected:false},
{id:4,name:"Year",isselected:false},
{id:5,name:"Badge Name",isselected:false},
]
}
class PDetail{
id!: number;
name!: string;
isselected!: boolean;
}
Here is the sample screenshot whenever I open the edit button.
sample screenshot
I understand that the reason why it is not showing a checkmarks is because of the getPlacardDetails() which is showing false value.
Is there a way that you can recommend a method how I can fix this?
I'm running out of resources and logic lol.
Sorry, still in-experience and I still have lots to learn.
Thank you in advance!
Use "checked" attribute of the checkbox to make it checked. Code as below:
<input type="checkbox" name="{{item.id}}" [(ngModel)]="item.isselected" [checked]="item.isselected">
Also for more details you can refer to below link:
Angular 5, HTML, boolean on checkbox is checked

how to loop through array using ngFor in angular 11

i have a api responce like
res.attribute
0: {relate_id: 15, pid: 9, attr_slug: "size", items: "s,m,l", id: 1, …}
1: {relate_id: 16, pid: 9, attr_slug: "color", items: "yellow", id: 2, …}
length: 2
i need two set of radio buttons for size and color..i achived that through
<section class="example-section" *ngFor="let attr of Attr" >
<mat-radio-button *ngFor="let checkbox of attr.items.split(',')" class="example-margin">{{checkbox}}</mat-radio-button>
</section>
but, every radio button is like same name(only one from all 4 (s,m,l,yellow) can be selected)
what i am expecting is two different set of radio buttons like size and color
You can bind the input property name with the radio type you want.
[name]="attr.attr_slug"
This way it has a radio group that will be group by your slug name.
<section class="example-section" *ngFor="let attr of Attr" >
<mat-radio-button *ngFor="let checkbox of attr.items.split(',')"
[name]="attr.attr_slug"
class="example-margin">{{checkbox}}</mat-radio-button>
</section>
You should be using a mat-radio-group to group up the radio buttons inside. Try it like below :
<section class="example-section" *ngFor="let attr of Attr" >
<mat-radio-group [name]="attr.attr_slug">
<mat-radio-button *ngFor="let checkbox of attr.items.split(',')" class="example-margin">{{checkbox}}</mat-radio-button>
</mat-radio-group>
</section>
Edit:
For getting the desired "s,yellow" or "m,yellow" output you can do a workaround below.
Since your slugs are size and color. Define a model has those properties in your component:
model = {
size = "",
color = "",
}
Bind the radio group to the corresponding properties like below
<mat-radio-group [name]="attr.attr_slug" [value]="model[attr.attr_slug]">
So later in your component get your combined value like this :
const finalValue = `${this.model.size}, ${this.model.color}`
As #Eldar said you need to include mat-radio-button inside mat-radio-group then you have two different sets of radio button groups. You can refer to the Angular Material docs here.

Multiple Checkbox value in angular2

I have one user model and one role model. I want to send value of role into db using checkbox in angular2 in http put request. I have one table user_role and I want to send role_id into that table. For the I am fetching all roles and showing it in html like this:
<a *ngFor="let role of roles">
<input type="checkbox" [value]="role.name" [(ngModel)]="user.role_id" [ngModelOptions]="{standalone: true}"/> <b>{{role.name}}</b>
</a>
Now I want, if I will check multiple checkboxes the multiple values should go into database. I am new in angular2. Could anyone please help me in getting this?
I have created a sample demo where you can understand how multiple checkbox value can be sent to server
here is my .ts file code
roles: Array<String> = [
{
"name":"qa",
"isSelected": false
},
{
"name":"developer",
"isSelected": false
},
{
"name":"manager",
"isSelected": false
},
{
"name":"BA",
"isSelected": false
},];
sendDataToServer() {
alert(JSON.stringify(this.roles)); }
I have a json roles and a function sendDataToServer that displays the final json that is to be sent on server
here is my .html code
<a *ngFor="let role of roles">
<input type="checkbox" [value]="role.name" [(ngModel)]="role.isSelected" [ngModelOptions]="{standalone: true}"/> <b>{{role.name}}</b>
</a>
<br><br>
<input type="button" value="Send Data On Server " (click)="sendDataToServer()"/>
So I have 4 checkbox and I have bind these checkbox with isSelcted property of json. As soon as user click on checkbox the value changes false to true.
when user click on sendDataToServer button then we have the updated isSelected values.
Hope this will help you. :)

Mvc razor radio button get default value from model

I've an Hotel model and there is a HotelPrice list in the model.
What i'm trying to do is when user display hotel detail page let hotel prices' info be shown, also they can be editable. I've a breakfastIncluded property on HotelPrice instances which i have to display as radio button.
Here is my code:
<div>
#{
foreach(var hotelPrice in Model.HotelPrices)
{
<label class="mt-radio-inline>
#Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "1", new { #checked = (hotelPrice.Breakfast.ToString() == "1") })Yes
<span></span>
</label>
<label class="mt-radio-inline>
#Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "0", new { #checked = (hotelPrice.Breakfast.ToString() == "0") })No
<span></span>
</label>
}
}
When i display my page(i could not come editing part, yet), all breakfastIncluded properties' radio buttons are displayed as unassigned and the last one's radio button is displayed wrongly(i.e it has to be "Yes" but it seems like "No").
However, when i checked by Inspect tool of browser, all of the radio buttons' checked property appears correct(i.e if it should be "Yes" that radio button's checked is true and "No"'s checked is false).
I'm new to html and i could not figure out why that happens. Can you help me? Thanks in advance.
By applying solutions in comments. I used for instead of foreach and it appears that i shouldn't set checked value since the radio buttons have values.

Knockout checked binding with no default

I am using Knockout to handle interactivity in a web app. I am trying to create a multiple-choice quiz widget. I want to present a question, and then a group of radio buttons which the user can pick from. I do not want a default answer.
I have the following in my code:
<!-- ko foreach: {data: answers, as: 'answer'} -->
<li class="list-group-item">
<input type="radio"
name="answers"
data-bind="checkedValue: answer, checked: $parent.current.problem.response">
<span data-bind="mathjax: answer.value.text">1.5</span>
</li>
<!-- /ko -->
Now, the Knockout documentation says:
When the user changes which radio button is selected, KO will set your model property to equal the value of the selected radio button. In the preceding example, clicking on the radio button with value="cherry" would set viewModel.spamFlavor to be "cherry".
So, based on the documentation, it is my understanding that the current.problem.response observable should be getting set to an answer object. But instead, it is getting set to on.
I think this is because my current.problem.response observable is initially null. This makes sense for my domain. It should be empty if the user hasn't made a selection.
What should I do?
Looks like your scenario works. Maybe the problem is out of the scene.
This fiddle demonstrates it works http://jsfiddle.net/tabalinas/y3LpD/
Open console to see selected option.
Demo view model looks like
var vm = {
answers: [
{ text: 'ans1' },
{ text: 'ans2' },
{ text: 'ans3' },
{ text: 'ans4' }
],
response: ko.observable(null)
};
vm.answer = vm.answers[0];
vm.response.subscribe(function(value) {
console.log(value);
});
The markup a little corrected according to the model
<!-- ko foreach: {data: answers, as: 'answer'} -->
<li class="list-group-item">
<input type="radio"
name="answers"
data-bind="checkedValue: answer, checked: $parent.response" />
<span data-bind="text: answer.text"></span>
</li>
<!-- /ko -->
Hope this can help. If you have any further problems, specify them in comments.