Add multiple checkboxes based on input length in Angular - html

Currently, I have a single checkbox in my Angular application which I plot using the HTML code:
<input type="checkbox" id="box1" value="Apple">
<label for="box1"> Apple</label>
However, I now need to tweak the functionality such that the number of checkboxes is dependant on the array input. Also, the contents of the arrays should be the labels for the checkboxes.
For ex:
If my array is arr = ['Apple', 'Mango','Banana'], I should get 3 checkboxes (as the length of arr is 3) like this:
How can I do this?

use *ngFor for acheiving this
app.component.html
<div *ngFor="let item of arr;">
<input type="checkbox" id="{{item}}" [value]="item " (change)="getItem($event)">
<label for="{{item}}"> {{item }}</label>
</div>
app.component.ts
arr = ['Apple', 'Mango','Banana'];
getItem(item) {
//check if the checkbox selected or not
if(item.target.checked) {
let value = item.target.value;
console.log(value);
//Do your thing here
}
}
Hope this help's :)

There is multiple way to achieve this.
HTML
<div *ngFor="let item of array; let i = index">
<input type="checkbox" [checked]="item.status" (click)="checked(i)">
<label> {{item.name}}</label>
</div>
<div *ngFor="let item of arr;">
<input type="checkbox" id="{{item}}" [value]="item ">
<label for="{{item}}"> {{item }}</label>
</div>
Class
array = [
{ name: "Apple", status: true },
{ name: "Mango", status: true },
{ name: "Banana", status: true }
];
checked(i) {
this.array[i].status = !this.array[i].status;
}
arr = ["Apple", "Mango", "Banana"];
You can also find working link: stackblitz

Related

Display all the data in a checkbox that are coming from the api in vuejs

I am facing an issue where i want to display the data of an array from api in checkbox. I have list of checkbox calling from another api and i want to show the selected values with checked in that list of checkbox but i cannot
Here is the sample of code:
<ul class="checkboxes">
<li v-for="(role, i) in roles" :key="i">
<input
:id="'checkbox' + i"
type="checkbox"
v-model="selected"
:value="role"
/>
{{ role.name }}
</li>
</ul>
All though all the checkbox are displaying but it is not displaying the ones with checked that are coming from backend.
For example: i have 10 values inside roles. but not showing checked in the page.
Roles looks like this:
roles:['x:list', 'y:list']
please help
I built a sample component showing how to bind an array of roles to checkboxes:
<template>
<div class="bind-multiple-checkboxes">
<h3>Select Roles</h3>
<div class="row">
<div class="col-md-6">
<div class="form-check" v-for="(role, index) in roles" :key="index">
<input class="form-check-input" type="checkbox" :id="'checkbox' + index" v-model="role.selected">
<label class="form-check-label" :for="'checkbox' + index">
{{ role.name }}
</label>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
roles: [
{
name: 'role1',
selected: true
},
{
name: 'role2',
selected: false
},
{
name: 'role3',
selected: false
},
{
name: 'role4',
selected: true
},
]
}
}
}
</script>
it is important that you have an empty array to bind the selected values in two ways. note that role.name does not exist, since role is a string in your array:
new Vue({
el: '#app',
data: {
roles: ['x:list', 'y:list', 'z:list'],
selected: ['z:list'] // fill if you want a checkbox prefilled
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id='app'>
<ul class="checkboxes">
<li v-for="role in roles" :key="role.id">
<label>
<input
type="checkbox"
:value="role"
v-model="selected"
/>
{{ role }}</label>
</li>
</ul>
<p>{{ selected }}</p>
</div>
you can read more about input bindings here

Angular 9 cannot check or uncheck checkbox

I have a table that is populated from an array coming from an API. The next thing I want to do is to add some checkboxes in a tab next to the table to filter data in the table. I'm adding the checkboxes dynamically because until the array comes from the API I don't know the filters (I know the category of the filters. ie Country or Language, but I don't know which countries or which languages will come in the array).
So, the problem is that I am trying to have a formArray to contain the checkboxes and I add to them programmatically as soon as I know what the values for the filters will be. But, when I try to click (just with my mouse) on the generated checkboxes I cannot. It doesn't check or uncheck.
However, if I just add the checkboxes without the formArray I can check and uncheck to my hearts content.
Here is my html for when I cannot check or uncheck (initially all of them are checked)
<form [formGroup]="languageForm">
<div *ngIf='results && results.length'>
<div class=" custom-control custom-checkbox mb-3" *ngFor="let item of languageForm.controls.filters.controls; let i = index" formArrayName="filters">
<input class=" custom-control-input" [formControlName]="i" id="i" type="checkbox" />
<label class=" custom-control-label" [for]="i">
{{ f_languages[i].label }}
</label>
</div>
</div>
</form>
Here is the html (for the one that does work)
<div *ngIf='results && results.length'>
<div class=" custom-control custom-checkbox mb-3" *ngFor="let item of f_countries; let i = index">
<input class=" custom-control-input" id="{{ item.value }}" type="checkbox" />
<label class=" custom-control-label" for="{{ item.value }}">
{{ item.value }}
</label>
</div>
</div>
Here is the TS for both (for the sake of the example I will make the filters static)
#Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
f_countries = [
{label: 'United States', value: 'US' },
{label: 'United Kingdom', value: 'UK' },
{label: 'Germany', value: 'DE' },
{label: 'Philippines', value: 'PH' }
];
f_languages = [
{label: 'English', value: 'EN' },
{label: 'German', value: 'DE' },
{label: 'French', value: 'FR' },
{label: 'Spanish', value: 'ES' }
];
//constructor omitted but nothing interesting there
ngOnInit() {
// search form init and other things
this.languagesForm = this.formBuilder.group({
filters: new FormArray([])
});
}
doSearch(): void {
this.searchService.search(this.searchForm.get('country').value, this.searchForm.get('language').value)
.subscribe(results => {
this.results = results;
this.slicedResults = this.results.slice(0, this.pageSize);
//load the filters
this.initializeFilters();
});
}
initializeFilters(): void {
//normally here the mapping from results to the filters
//but omitted since I said that for the example the filters are static
this.f_languages.forEach((o, i) => {
const control = new FormControl(true);
(this.languagesForm.controls.filters as FormArray).push(control);
});
}
Thanks in advance for all the help, I'm sure it's something stupid that I just cannot see anymore after staring at it for so many hours.
EDIT -- I don't know exactly why this worked but it did. See below my final html which is now mysteriously clickable
<form [formGroup]="languagesForm">
<div *ngIf='results && results.length'>
<div class=" custom-control custom-checkbox mb-3" *ngFor="let item of languagesForm.controls.filters.controls; let i = index" formArrayName="filters">
<input checked="checked" class=" custom-control-input" id="{{ i }}" [formControlName]="i" [value]="f_languages[i].value" type="checkbox" />
<label class=" custom-control-label" [for]="i">
{{ f_languages[i].label }}
</label>
</div>
</div>
</form>
Apparently if it doesn't have id in the input and for in the label the thing is not un/checkable. Maybe someone will be able to explain why...

How can I access the checked property of a checkbox which is indexed by an *ngFor loop - Angular

I have a list of drop-down elements, which is indexed by an *ngFor loop.
<div class="item-wrapper" *ngIf="showItems">
<div class="wrap-collapsible" *ngFor="let item of items; let i = index">
<input id="{{i}}" class="toggle" type="checkbox">
<label for="{{i}}" class="dropdown-toggle" tabindex="0" (click)="selectItem(item)">
Threat {{item.id}}: {{item.category}}
</label>
<div class="collapsible-content">
<div class="content-wrapper">
<p class="title">{{item.title}}</p>
</div>
</div>
</div>
</div>
Per default, the checkbox input is selected on click, and stays checked when selecting other elements.
How would I go about unchecking all elements except the last one clicked?
I've tried doing...
<input id="{{i}}" type="checkbox" [checked]="i == selectedElement">
...while passing the index in the selectItem() method, where selectedElement is set to i. This doesn't work, because then no item is selectable.
Can anyone give me a push in the right direction?
Bind to the change function of your input :
<input id="{{i}}" class="toggle" type="checkbox" (change)="setLastClicked(item)">
In your TS :
setLastClicked(item) {
this.lastSelected = item;
}
You can now use that memory reference to compare to the items when you [un]check them all :
toggleCheck() {
this.items.forEach(item => item.checked = {
if(item === this.lastSelected) return;
item.checked = !item.checked;
});
}
With a memory reference, you don't need the ID anymore.

How to get the values of multiple checkboxes in typescript file using angular 6?

I have 8 to 10 checkboxes in my html. I need to send the checked checkboxes values to my typescript file.
<div>
<input type="checkbox" value="one" id="one" name="num">
<input type="checkbox" value="two" id="two" name="num">
<input type="checkbox" value="three" id="three" name="num">
<input type="checkbox" value="four" id="four" name="num">
</div>
How do I get all the selected checkboxes values in my ts file? Can somebody help me with this?
You could use an array containing informations on your checkboxes, ngFor loop and ngModel:
checkboxes = [
{
value: 'one',
selected: false
},
{
value: 'two',
selected: false
},
{
value: 'three',
selected: false
},
{
value: 'four',
selected: false
}
]
Your html :
<div>
<input *ngFor="let ch of checkboxes" [(ngModel)]="ch.selected" type="checkbox" value={{ch.value}} id={{ch.value}} name="num">
</div>
<button (click)="getSelected()">Print selected checkboxes</button>
And the getSelected() function:
public getSelected() {
let result = this.checkboxes.filter((ch) => { return ch.selected })
.map((ch) => { return ch.value });
console.log(result);
}

how to make radio buttons selected in angularjs

i am new to angularjs and javascript,I am having a list of radio buttons and have to make some of them selected,so can anybuddy please tell me how to achieve this?I tried ng-value=true with no luck,my code is as below:
<ons-list-item modifier="tappable" ng-repeat="area in vm.AreaList" >
<label class="radio-button radio-button--list-item line-h45">
<input type="radio" ng-bind="area.name" ng-model="vm.selectedArea" name="area" ng-value="area.code" >
<div class="radio-button__checkmark radio-button--list-item__checkmark">
</div>
{{area.name}}
</label>
</ons-list-item>
you can do something like this in your controller:
$scope.results = {
favorites: [{
id: "WatchList1",
title: "WatchList1"
}, {
id: "WatchList2",
title: "WatchList2"
}, {
id: "WatchList3",
title: "WatchList3"
}]
};
$scope.selectedRow = {
id: 'WatchList2'
};
$scope.event = {
type: {
checked: true
}
}
and your html:
<div>
<div ng-repeat="row in results.favorites">
<input type="radio" ng-model="selectedRow.id" value="{{ row.id }}" style="opacity: 1;" class="pointer" />
<span>{{ row.title }}</span>
</div>
</div>
Single box
You should use ngChecked for that.
https://docs.angularjs.org/api/ng/directive/ngChecked
<ons-list-item modifier="tappable" ng-repeat="area in vm.AreaList" >
<label class="radio-button radio-button--list-item line-h45">
<input type="radio" ng-bind="area.name" ng-model="vm.selectedArea" name="area" ng-value="area.code"
ng-checked="true">
<div class="radio-button__checkmark radio-button--list-item__checkmark">
</div>
{{area.name}}
</label>
</ons-list-item>
Only one radio button can be selected at a time.
If you want multiple selected items, then use checkbox and to select, make model value equal to value attribute.