I have this checkbox
<div *ngFor="let user of userList">
{{ userList.Name }}
<input type="checkbox" (change)="selectUser($event,user)">
</div>
selectUser(event,user)
{
if (event.target.checked) {
const userDetails = {
userID: user.UserID,
Name:Name ,
};
this.tempLists.push(userDetails);
}
else
{
this.tempLists= this.tempLists.filter(function(obj) {
return obj.userID !== user.UserID;
});
}
}
in this method I'm adding the selected user to the array, but i want that if id is present in the array then when reloading the content where checkbox is present, the checkbox should be selected if that particular id is present in the array.
You need to merge the userList and the tempLists in order to put a property checked on userList and then just add [checked]="user.checked"
The merge part:
userList.map(u =>{
const potentialTempLists = tempLists.find(t => t.UserID === u.UserID)
return potentialTempLists ? {...u, checked: true} : u
});
You can create a function that will check if user is there in the temp list and based on that you can mark checkbox as checked so in you ts file
isChecked(user){
return this.tempLists.some(u=> u.userID==user.UserID);
}
Then on UI user this function to see if user is checked or not
<input type="checkbox" [checked]="isChecked(user)" (change)="selectUser($event,user)">
Working demo
Related
I'm trying to make item swap in 2 array. There are 2 lists in the ui and the user select the
items in the first list, then it should get removed from the 1st list and moved to 2nd list, where there are shown the selected items. The problem I got is that when I try to move the elements from the 1st and 2nd list with the setValue it doesen't change the value value.
The function getIndexA works, I use it because I have an array of object and in the input as value I have a proprierty of the object (the key).
(If I print array before removing the object and after removing the object I see the array is correctly removing the object but when I setListaFile it doesen't change ListaFile values (even if I uncheck and recheck the input I see that array2 is made of the element selected and undefined) so it seems to work, but in render I still se the list as same of start (even with an useState connected to listaFile with a console log it doesen't show the console log of listaFile)
const [fileSelezionati,setFileSelezionati] = useState([]);
const [listaFile,setListaFile] = useState([]);
function handleCheck(e){
if(e.target.checked){
var array = listaFile;
var item = listaFile[getIndexA(listaFile,e.target.value)];
array.splice(getIndexA(listaFile,e.target.value),1);
setListaFile(array);
var array2 = fileSelezionati;
array2.push(item);
console.log("array2:",array2);
setFileSelezionati(array2);
}
}
This part is in the return()
<ul>
{
listaFile.map((file,index)=>{
return <div key={file.key}><input type="checkbox" value={file.key}
onChange={(e)=>handleCheck(e)}/> {file.key}</div>
})
}
</ul>
<label>File selezionati:</label>
<ul>
{
fileSelezionati.map((file,index)=>{
return <div><input key={file.key} type="checkbox" value={file.key}
checked={true}>{file.key}</input></div> })
}
</ul>
you can do this
<ul>
{
listaFile.map((file,index)=>{
return <div key={file.key}><input type="checkbox" value={file.key}
onChange={(e)=>handleCheck(file.key, e.target.checked)}/> {file.key}</div>
})
}
</ul>
<label>File selezionati:</label>
<ul>
{
fileSelezionati.map((file,index)=>{
return <div><input key={file.key} type="checkbox" value={file.key}
checked={true}>{file.key}</input></div> })
}
</ul>
const [fileSelezionati,setFileSelezionati] = useState([]);
const [listaFile,setListaFile] = useState([]);
function handleCheck(key, checked){
if(checked){
const item = listaFile.find(f => f.key === key)
setListaFile(listaFile.filter(f => f.key !== key));
setFileSelezionati([...fileSelezionati, item]);
}
}
I am trying to disable buttons that the logged in user have voted on, however, when I use the disabled directive inside my ngFor (in the example below) all of the buttons are disabled, not just the items that include the logged in user. My goal is to check to see if an array contains the current user's uid, if so disable the button. How can I achieve this? Thanks in advance
compontent.ts:
this.itemsCollection = this.afs.collection('food', ref => ref.orderBy('voteCount', 'desc'));
this.items = this.itemsCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
this.afAuth.authState.subscribe(user => {
if(user) {
this.user = user.uid;
if (data.votedBy.includes(user.uid)){
console.log(id);
console.log('you already voted');
this.disabledButton = true;
return false;
}
else {
this.disabledButton = false;
}
}
});
return { id, ...data };
}))
);
html:
<div class="firestoreLoop" *ngFor="let item of items | async" >
<div class="container1">
<div class="card">
<div class="card-body">
<p>{{item.voteCount}}</p>
<p>{{item.id}}</p>
<p>{{item.votedBy}}</p>
<p>{{user}}</p>
</div>
<button type="button" id="item.id" class="btn"(click)="upvote(item.id)" [disabled]="disabledButton">Upvote</button>
</div>
</div>
</div>
Edit: I got the desired result by adding *ngIf= "user != item.votedBy" to the button. Thanks for the help gentleman.
best way for you is to add disabledButton as a property of item in items array,
and then the [disabled] on the button should be [disabled]="item.disabledButton".
And then you can control which item should be disabled by simply identifying the user and setting its corresponding item's disabledButton property to true otherwise false
In my angular application, I am looping through a collection and displaying the records with input type="radio".
<tr ng-repeat="account in vm.pagedAccounts.items"
ng-class="{ 'highlight': (account.rowIsSelected) }"
<td>
<input
ng-model="account.rowIsSelected"
value="{{account}}"
name="selectedAccount"
ng-checked="account.rowIsSelected"
ng-change="vm.selectAccount(account)"
type="radio">
</td>
In my controller, I first set rowIsSelected property to false for all the accounts.
response.data.results.forEach(function(account) {
account.rowIsSelected = false;
});
So, I just make sure whenever account.rowIsSelected is set to something, make that checked.
This is working fine.
But, in the selectAccount function, if a different account is clicked, I want to remove the previous all highlights and highlight the current one.
vm.selectAccount = function (account) {
if (account.rowIsSelected) {
//First set all false
vm.pagedAccounts.items.forEach(function(account) {
account.rowIsSelected = false;
});
var selectedAccount = vm.pagedAccounts.items
.filter(function(x){
return x.id=== account.id;
});
//Then set only that accounts property to true
selectedAccount[0].rowIsSelected = true;
}
But if I click the same row twice, it is no longer checked. I want to keep it checked and highlighted.
How to do it?
Does whatever I am doing seem right?
Please help.
Try this.
vm.selectAccount = function (checkedItem) {
var selectedAccount;
vm.pagedAccounts.items.forEach(function(account) {
if(checkedItem.id == account.id){
selectedAccount = account;
account.rowIsSelected = true;
}else{
account.rowIsSelected = false;
}
});
//Then set only that accounts property to true
selectedAccount[0].rowIsSelected = true;
}
I think you should organize your radio buttons in a bit different way, like it recommends angularjs
Something like:
<tr ng-repeat="account in vm.pagedAccounts.items"
ng-class="{ 'highlight': vm.pagedAccounts.selected === account }">
<td>
<input
ng-model="vm.pagedAccounts.selected"
ng-value="account"
type="radio">
</td>
...
And radio buttons should be automatically selected, when ng-model values is equal to ng-value, so you don't need any specific logic or ng-checked, etc.
This is simple one but i still somehow couldn't get it to work.
I have default value checked, checkbox. So when edit, of course the default value is chosen, but later I want to remove the default value and choose another value. Here it is
array1=[] //empty
After I check a checkbox, it will inserted to this array
array1=["sun"]
If I select 3 values (array1["sun","stars","moon"])
but I deselect the first selection (the default selection), it will be still in the array. (array1["sun","stars","moon"]) but I the expected result is this:
array1["stars","moon"]
No more first selection. So how to remove deselected value from array using Angular/Javascript?
I have tried use splice, remove and set
Same thing developed and used in project :
Template side :
<label *ngFor="let hobby of hobbies" #checkbox class="mdl-checkbox mdl-js-checkbox">
<input type="checkbox" name="hobbies" [value]="hobby"
(change)="populateMyHobbies(hobby,$event.target.checked)" class="mdl-checkbox__input">
<span class="mdl-checkbox__label">{{hobby}}</span>
</label>
Component Side :
selectedHobbies = [];
populateMyHobbies(value , status:boolean)
{
if(this.selectedHobbies.indexOf(value) === -1 && status)
{
this.selectedHobbies.push(value);
}
else if(!status)
{
let index = this.selectedHobbies.indexOf(value);
this.selectedHobbies.splice(index, 1);
}
}
Here selectedHobbies will give you what you want.
Have to change just name as per your app.
i used it once in my project. change the code according to your need. logic is same.
html part
<input type="checkbox" value="{{category._id}}" (change)="pushpopcategory(category._id)" id="{{category._id}}">
component code
pushpopcategory(value) {
if ((<HTMLInputElement>document.getElementById(value)).checked) {
this.categoryAdd.push(value);
} else {
let indexx = this.categoryAdd.indexOf(value);
this.categoryAdd.splice(indexx, 1);
}
}
I got a checkbox list populated by my viewmodel. I specify id and value in the checkbox element. I need to save these information in the database. Currently i have it where i take the checkbox id and checkbox value, puts them in a key value pair and i intend to make an ajax call to my controller. Is there a better approach into doing this (mvc)? How would you do it?
Thanks
My code:
VIEW
<div class = "divSubject">
#foreach (var item in Model.dictionarySubject)
{
<div>
#Html.CheckBoxFor(model => item.Value, new { #id = item.Key.subjectID})
#Html.DisplayFor(model => item.Key.subjectName)
</div>
}
</div>
JQuery
$("#btnSave").click(function () {
var dict = []; // create an empty array
$('.divSubject input[type=checkbox]').each(function () {
var id = $(this).attr('id')
dict.push({
key: id,
value: $(this).attr('checked')
});
alert(JSON.stringify(dict))
});
}
The id of a DOM element has some limitations. For example it cannot start with a number. I would recommend you using the HTML5 data-* attributes to hold this metadata information:
#Html.CheckBoxFor(
model => item.Value,
new { data_id = item.Key.subjectID }
)
and then inside your javascript:
$('.divSubject input[type=checkbox]').each(function () {
var id = $(this).data('id')
dict.push({
key: id,
value: $(this).attr('checked')
});
alert(JSON.stringify(dict))
});
Other than that your code seems fine.
Your code works just fine, but I believe that you want to take pairs of key and Boolean value. In this case, consider below code:
dict.push({
key: id,
value: !!$(this).attr('checked')
});
$(this).attr('checked') will return "checked" or null, not a Boolean value.