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. :)
Related
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
In an Angular 12 app the data returned from an API is
data = {
"options":[
{
"Yes": 1
},
{
"No": 0
}
]
}
My requirement is to iterate over this array and display radio buttons dynamically in the html as shown below.
<div *ngFor="let option of data.options;">
<input type="radio" class="form-control" name="rdgroup" value="{{option.key}}">
<label>{{option.value}}</label>
</div>
I want display labels for radio buttons to be 'Yes' and 'No' and their values should be 1 and 0 respectively. Currently nothing is displayed. How do I fix it?
You will need to modify you data in order to render radio buttons.
Check this stackblitz: https://stackblitz.com/edit/angular-material-with-angular-sidenav-spz9oq?file=app/app.component.html
Use the below method on your component:
options = this.data.options.map( (op) => {
const key = Object.keys(op)[0];
return {
"value" : Object.keys(op)[0],
"key": op[key]
}
});
and in template
<div *ngFor="let option of options;">
<input type="radio" class="form-control" name="rdgroup" value="{{option.key}}">
<label>{{option.value}}</label>
</div>
You can try in this way, It may help you to get expected output!
edit your component.ts file, and add below defined method.
getEntrires(object: any) {
return Object.entries(object);
}
this method will return you Object entry with it's KEY & VALUE in Array
For Example:
let output = getEntrires({"Yes": 1});
console.log(output) // [Array[2]] => it will be two dimensional array
Now in your html you can consume this in this way
<div *ngFor="let option of data.options;">
<input type="radio" class="form-control" name="rdgroup" value="{{getEntrires(option)[0][1]}}">
<label>{{getEntrires(option)[0][0]}}</label>
</div>
I am new to Angular and typescript. I need help from someone in the following requirement.I have a web page where I have a list of check boxes as given here:
I have defined a isChecked boolean variable in component.ts file and has a data binding with the template using ngModel. A function onChange() is called when the checkbox is checked or un-checked. I want to pass two parameters to the function. One is check/uncheck value i.e like true/false and another is the string value containing the label of the checkbox clicked. For example if st1 is checked then onChange(check, 'st1') will be invoked. The logic inside component class will add 'st1' to an array if it is unchecked.
In the template I have written like this:
<ul>
<li [(ngModel)]="student" *ngFor="let student of studentsToLOad" [value]="student">
<b>{{student.name}}</b>
<input type="checkbox" id="present" name="present" [(ngModel)]="isChecked"
(change)="onChange(isChecked, student)"/>
</li>
</ul>
But when I am clicking on st1, all the other check boxes are also getting checked. Please help.
The ngModel value is set to a single variable isChecked. This variable is passed to all checkboxes. All the checkboxes will reflect their state based on isChecked. You could use some thing like student.checked. You could set the value in the onChange fucntion.
onChange(isChecked, student) {
student.isChecked = isChecked;
}
<ul>
<li [(ngModel)]="student" *ngFor="let student of studentsToLOad" [value]="student">
<b>{{student.name}}</b>
<input type="checkbox" id="present" name="present" [(ngModel)]="student.isChecked" (change)="onChange(isChecked, student)" />
</li>
</ul>
The error occurs because all the checkboxes are bound to a single global boolean flag isChecked.
You could remove the ngModel and value from the li element and bind the ngModel in input element to student specific booleans instead of a global boolean flag. Try the following
Controller
export class AppComponent {
studentsToLOad = [
{ name: 'st1', status: false },
{ name: 'st2', status: false },
{ name: 'st3', status: false },
{ name: 'st4', status: false },
];
onChange(status, name) {
console.log(name, status);
}
}
Template
<ul>
<li *ngFor="let student of studentsToLOad">
<b>{{student.name}}</b>
<input type="checkbox" id="present" name="present" [(ngModel)]="student.status"
(change)="onChange(student.status, student.name)"/>
</li>
</ul>
I am very new to spring mvc world. I am trying to send boolean value to from html form checkbox. When a user check the checkbox then it will send true, false otherwise.
<form class="attendanceBook" role="form" method="post" action="/attendances">
<div class="row">
<div class="form-group">
<div class="col-xs-4">
<label class="control-label">Check Here</label>
</div>
<div class="col-xs-4">
<input type="checkbox" name="i" id="i" value="true" />
</div>
<div class="col-xs-4">
<input type="submit" value="Click"/>
</div>
</div>
</div>
</form>
After some googilng I have found this so post, where it said standard behaviour is the value is only sent if the checkbox is checked. So what I have understand that is if the checkbox checked then the form will submit with the value of checkbox, otherwise it will not submit. When there is unchecked checkbox the initialization value in data class will be effective.
But in my case every time I am submitting the form it submitting true.
here is my rest controller for the bind html form submit.
#RestController
#RequestMapping("attendances")
class AttendanceRestController {
val logger = getLogger(AttendanceRestController::class.java)
#PostMapping
fun patchAttendance(#RequestBody attendanceJson: AttendanceJson): ResponseEntity<*> {
logger.info("attendanceJson {}", attendanceJson)
return responseOK(attendanceJson)
}
}
the data class(I am using kotlin)
data class AttendanceJson (
var i: Boolean = false,
var t: String = ""
)
So what will be the method to bind boolean data from a form submission with checkbox. I am also using Thymeleaf. Thanks in advance.
I'm working in Struts and don't know much about Spring. But I faced a similar situation.
What I did was I binded the checkbox with a boolean property in my From class. So for each checkbox, one boolean variable. And at the time of submitting in front end, I'll call a JS function code is below
function verifyCheckboxes() {
document.getElementById("researchPaper").value = document.getElementById("researchPaper").checked;
document.getElementById("researchPaperSeminarProceed").value = document.getElementById("researchPaperSeminarProceed").checked;
document.getElementById("extraActivities").value = document.getElementById("extraActivities").checked;
document.getElementById("studentAchivements").value = document.getElementById("studentAchivements").checked;
}
Here you can see I'm just assigning the value of checked property of that Checkbox just before submitting. It will be either true or false.
You should remove 'value' attribute from the input. If you want the checkbox checked when loading the page, add 'checked' attribute not 'value'.
Replace the input line with this:
<input type="checkbox" name="i" id="i" checked="checked"/>
This is the reason why you always get 'true' in code behind.
It's a bit of a hack, but if you change the type of the input tag from 'checkbox' to 'text' just before the form is posted, you will receive the value, whether it is checked or unchecked.
If you use jQuery:
$("input:checkbox").each(function(){this.type='text'})
I'm newbie in Angular2 and in web globally , I want to launch an action that changes an oject paramater value in the Database when checking a checkbox and or unchecking it using Material-Design, I tried with [(ngModel)] but nothing happened. the idea is that i have to add some propositions with checked | unchecked status to tell if it is a true or false proposition. Here is the proposition model
export class PropositionModel {
id:string;
wordingP:string; // the proposition
propStatus:Boolean; // the proposition status
}
here is the Html code for a proposition :
<div class="uk-width-xlarge-1-1 uk-width-medium-1-2">
<div (submit)="addProp1()" class="uk-input-group">
<span class="uk-input-group-addon"><input type="checkbox" data-md-icheck/></span>
<label>Proposition 1</label>
<input [(ngModel)]="proposition1.wordingP" type="text" class="md-input" required class="md-input"/>
</div>
</div>
here is the TypeScript code for adding the proposition:
addProp1() {
this.proposition1 = new PropositionModel();
this.proposition1.propStatus = false;
this.propositionService.addProposition(this.proposition1)
.subscribe(response=> {
console.log(response);
console.log(this.proposition1);
this.proposition1 = new PropositionModel();})
}
And as you can see i made it a false by default for the proposition status and I want to change it once i checked the proposition.
Here is an image how it looks for a better issue understanding.
Any help Please ?
StackBlitz
Template: You can either use the native change event or NgModel directive's ngModelChange.
<input type="checkbox" (change)="onNativeChange($event)"/>
or
<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>
TS:
onNativeChange(e) { // here e is a native event
if(e.target.checked){
// do something here
}
}
onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
if(e){
// do something here
}
}
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
You can use ngModel like
<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.
Check Demo: https://stackblitz.com/edit/angular-6-checkbox?embed=1&file=src/app/app.component.html
CheckBox: use change event to call the function and pass the event.
<label class="container">
<input type="checkbox" [(ngModel)]="theCheckbox" data-md-icheck
(change)="toggleVisibility($event)"/>
Checkbox is <span *ngIf="marked">checked</span><span
*ngIf="!marked">unchecked</span>
<span class="checkmark"></span>
</label>
<div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>