Disable angular 2 multiselect checkboox - javascript

I would like to know if there is a possible way to disable certain checkbox items that is present in the multiselect dropdown. The multiselect has an option to disable the whole dropdown but I would like to know if we can disable particular checkboxes. For the below code, is there a way to disable the default selected checkbox values.
TS
import { Component, OnInit } from '#angular/core';
export class AppComponent implements OnInit {
dropdownList = [];
selectedItems = [];
dropdownSettings = {};
ngOnInit(){
this.dropdownList = [
{"id":1,"itemName":"India"},
{"id":2,"itemName":"Singapore"},
{"id":3,"itemName":"Australia"},
{"id":4,"itemName":"Canada"},
{"id":5,"itemName":"South Korea"},
{"id":6,"itemName":"Germany"},
{"id":7,"itemName":"France"},
{"id":8,"itemName":"Russia"},
{"id":9,"itemName":"Italy"},
{"id":10,"itemName":"Sweden"}
];
this.selectedItems = [
{"id":2,"itemName":"Singapore"},
{"id":3,"itemName":"Australia"},
{"id":4,"itemName":"Canada"},
{"id":5,"itemName":"South Korea"}
];
this.dropdownSettings = {
singleSelection: false,
text:"Select Countries",
selectAllText:'Select All',
unSelectAllText:'UnSelect All',
enableSearchFilter: true,
classes:"myclass custom-class"
};
}
onItemSelect(item:any){
console.log(item);
console.log(this.selectedItems);
}
OnItemDeSelect(item:any){
console.log(item);
console.log(this.selectedItems);
}
onSelectAll(items: any){
console.log(items);
}
onDeSelectAll(items: any){
console.log(items);
}
}
HTML
<angular2-multiselect [data]="dropdownList" [(ngModel)]="selectedItems"
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onDeSelect)="OnItemDeSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDeSelectAll)="onDeSelectAll($event)"></angular2-multiselect>

in dropdownList: you can add additional key to options you want to disable, like this:
{ id: 1, itemName: 'India', disabled: true }
and then in html use custom Template like this:
<angular2-multiselect [data]="dropdownList" [(ngModel)]="selectedItems"
[settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
(onDeSelect)="OnItemDeSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDeSelectAll)="onDeSelectAll($event)">
<c-badge>
<ng-template let-item="item">
<label style="color: #333;min-width: 150px;">{{item.itemName}}</label>
[disabled]="item.disabled"
</ng-template>
</c-badge></angular2-multiselect>
Here is the working example:
https://stackblitz.com/edit/angular2-multiselect-dropdown-tsqghc?file=src%2Fapp%2Fapp.component.html

You can disable a specific options from the template by using : [disabled] inside the options.
for example:
<mat-form-field appearance="fill">
<mat-label>Choose an option</mat-label>
<mat-select [disabled]="disableSelect.value">
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2" disabled>Option 2 (disabled)</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
</mat-form-field>
from Angular Material Select
as you can see in option 2 you have the "disabled" , you can change it to input and pass it from your list or just set disabled for the first option.
you can add the HTML file and then I can edit and add the full code.

Related

How to make a checkbox checked based on its parent div clicked inside ngFor?

I have a list of checkboxes inside ngFor. Each checkbox has its own parent div. I want checkboxes to be checked once the div clicked.
Here is my code.
<div *ngFor="let option of qustions; let i = index" (click)="doCheckboxCheck()">
<input type="checkbox" [value]="option.value">
<span>Checkbox {{i}}</span>
</div>
You could assign an Angular template reference variable to the <input> element and toggle it's checked property in the <div>'s click or mouseup event.
Now this could modify the default behavior of checkbox's own click event, so you could bind the [checked] toggle to <input> too.
<div
class="checkbox-container"
*ngFor="let option of questions; let i = index"
(mouseup)="inputCheckbox.checked = !inputCheckbox.checked"
>
<input
#inputCheckbox
class="checkbox"
type="checkbox"
[value]="option.value"
(mouseup)="inputCheckbox.checked = !inputCheckbox.checked"
>
<span>Checkbox {{ option.value }}</span>
</div>
Working example: Stackblitz
We can change the state of the checkbox on div click by passing the index to the even handler. Please refer to the link below which is having a working solution,
import { Component } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
questions = [
{ value: "Checkbox-1", checked: false },
{ value: "Checkbox-2", checked: false },
{ value: "Checkbox-3", checked: false },
{ value: "Checkbox-4", checked: false },
{ value: "Checkbox-5", checked: false }
];
doCheckboxCheck(index: number): void {
this.questions[index].checked = !this.questions[index].checked;
}
}
Template:
<div *ngFor="let option of questions; let i = index" (click)="doCheckboxCheck(i)">
<input type="checkbox" [value]="option.value" [checked]="option.checked">
<span>Checkbox {{i}}</span>
</div>
editor url - https://stackblitz.com/edit/checkbox-click?file=src/app/app.component.ts

How to solve no value in select when ngModel changes?

A project contains a component and a service.
Component injects the service and uses services field filter. There is a select in the components hmtl. [(ngModel)] of the select is binded to filter.sizes.width.
The component:
#Component({
selector: 'app-facet-sizes-static',
templateUrl: './facet-sizes-static.component.html',
styleUrls: ['./facet-sizes-static.component.scss']
})
export class FacetSizesStaticComponent implements OnInit {
constructor(
private Search: SearchService
) {
this.filter = Search.filter;
}
clearFilter() {
this.filter.sizes.width = 0;
}
}
Its template:
<div (click)="clearFilter()"></div>
<!-- Comment_01 -->
{{filter.sizes.width}}
<div *ngIf="filter.sizes">
<select name="width"
[(ngModel)]="filter.sizes.width">
<option [ngValue]="null">~</option>
<option *ngFor="let item of facet.sizes[0].parts.width; let x = index"
[ngValue]=item>
{{ item }}
</option>
</select>
</div>
The service:
export class SearchService {
filter: SearchServiceFilter = null;
constructor() {
this.filter = {
sizes: {
width: 0
},
};
}
}
When I change option in select it changes filter.sizes.width as I exapt. But there are two problems:
when component is inited there is no value in the select but filter.sizes.width has 0 value. I can check it watching the string {{filter.sizes.width}} under Comment_01
when the method clearFilter() changes filter.sizes.width there is becomes again no value in the select.
How do I solve it?
It sounds like your facet.sizes[0].parts.width array does not contain a value === 0. I see your option with a value of null, but null does not equal 0 and will not be selected. If you add an option with a value === 0; it should select it.

Matselect default values based on radiobuttons

I have three matformfields named Form A,Form B,Form C and three mat radio buttons named A,B,C.
What I want is that when radiobutton A is enabled or checked Form A's default value should be A and in other two form fields there should be no value by default. When radiobutton B is enabled or checked Form B's default value should be B and in other two form fields there should be no value by default.I want the same for radiobutton C. I am getting the dropdown data from service.
Sample data:
listes: any[] = [
{ id: 1, name: "A" },
{ id: 2, name: "B" },
{ id: 3, name: "C" },];
WHAT I HAVE TRIED:
I tried to get the id 1 which has value A and used setvalue to patch it in Form A but its not worling
const toSelect = this.listes.find(c => c.id == 1);
this.patientCategory.get('patientCategory').setValue(toSelect);
STACKBLITZ: https://stackblitz.com/edit/how-to-set-default-value-of-mat-select-when-options-are-reo3xn?file=app%2Ftable-basic-example.html
I've corrected your code as per the scenario you described. Although my temporary code is a little lengthy, it applies the logic you described. But I hope you simplify it further.
Fix:
[value] attribute of a mat-option shouldn't be set to category itself as category is an object. [value] expects a singular uniquely identifying value. So you should set it to [value] = "category.name". Ideally, we set value to unique identifiers like [value]="category.id" or [value]="category.key" etc.
The three mat-selects should behave independently in your scneario. So they should never be assigned to the same formControl. Instead, assign individual formControls to have full control over them.
Finally, you can use the function valueChange assigned to the radio buttons, to conditionally apply values in FormA, FormB and FormC as per your scenario.
<form [formGroup]="patientCategory">
<mat-form-field class="full-width">
<mat-select placeholder="FORMA" formControlName="patientCategoryA">
<mat-option *ngFor="let category of listes" [value]="category.name">
{{category.name}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="full-width">
<mat-select placeholder="FORMB" formControlName="patientCategoryB">
<mat-option *ngFor="let category of listes" [value]="category.name">
{{category.name}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="full-width">
<mat-select placeholder="FORMC" formControlName="patientCategoryC">
<mat-option *ngFor="let category of listes" [value]="category.name">
{{category.name}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
<div class="container" style="margin-top: 0px;">
<div class="example-container">
<mat-radio-group #group="matRadioGroup" [(ngModel)]="test" [(value)]="selectedValue"
(change)="onValueChange(group.value)">
<mat-radio-button value="A" [checked]="defaultSelected">A</mat-radio-button>
<mat-radio-button style="margin-left:10px" value="B">B</mat-radio-button>
<mat-radio-button style="margin-left:10px" value="C">C</mat-radio-button>
</mat-radio-group>
</div>
</div>
import { Component, ViewChild } from "#angular/core";
import {
FormBuilder,
FormGroup,
FormControl,
Validators
} from "#angular/forms";
import { DataService } from "./data.service";
/**
* #title Basic table
*/
#Component({
selector: "table-basic-example",
styleUrls: ["table-basic-example.css"],
templateUrl: "table-basic-example.html"
})
export class TableBasicExample {
patientCategory: FormGroup;
listes: any[];
constructor(private fb: FormBuilder, private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().subscribe(res => {
this.listes = res;
});
this.patientCategory = this.fb.group({
patientCategoryA: [null, Validators.required],
patientCategoryB: [null, Validators.required],
patientCategoryC: [null, Validators.required]
});
}
onValueChange(value) {
if (value === "A") {
this.patientCategory.get("patientCategoryA").setValue(value);
this.patientCategory.get("patientCategoryB").setValue(null);
this.patientCategory.get("patientCategoryC").setValue(null);
} else if (value === "B") {
this.patientCategory.get("patientCategoryB").setValue(value);
this.patientCategory.get("patientCategoryA").setValue(null);
this.patientCategory.get("patientCategoryC").setValue(null);
} else if (value === "C") {
this.patientCategory.get("patientCategoryC").setValue(value);
this.patientCategory.get("patientCategoryB").setValue(null);
this.patientCategory.get("patientCategoryA").setValue(null);
}
}
}
Hope this helps. Let me know if you have any issues.

Angular 7, how can I control ng-select options by selecting other ng-select value?

So I have two ng-select in my code, and if I select first ng-select value, I want to hide the same select option from the second ng-select. But I dont know how to control it. I wanted to use Jquery with, but no chance.
Both sourceLangCodeList and targetLangCodeList has values [ EN, KR ]
So the thing I want to try, once I select the value of one of ng-select, hide the same value the second ng-select has. Plz help!
<td>
<div class="form-group">
<ng-select
id="sourceLangSelect"
bindLabel="language"
bindValue="language"
formControlName="sourceLangCode"
[items]="sourceLangCodeList"
(change)="onChange($event)"
></ng-select>
</div>
</td>
<td></td>
<td>
<div class="form-group">
<ng-select
id="targetLangSelect"
bindLabel="language"
bindValue="language"
formControlName="targetLangCode"
[items]="targetLangCodeList"
></ng-select>
</div>
</td>
Please add a ngModel to slectedSoureclang and Onchange Filter the targetLangCodeList
<ng-select
id="sourceLangSelect"
bindLabel="language"
bindValue="language"
formControlName="sourceLangCode"
[items]="sourceLangCodeList"
(change)="onChange($event)"
[(ngModel)]="selectedSourceLang"
></ng-select>
Change Event
onChange(event){
const newlist = targetLangCodeList.filter((lang)=>lang!==this.selectedSourceLang);
targetLangCodeList = [...newlist];
}
Since you are using ReactiveForms, I will answer in ReactiveForm way.
Check out the full code at https://stackblitz.com/edit/m3yevn-ng-select-demo
Template:
<div class="form-group" [formGroup]="formGroup">
<ng-select id="sourceLangSelect" bindLabel="language" bindValue="language" formControlName="sourceLangCode"
[items]="sourceLangCodeList"></ng-select>
<ng-select id=" targetLangSelect" bindLabel="language" bindValue="language" formControlName="targetLangCode"
[items]="targetLangCodeList"></ng-select>
</div>
Component
import { Component, Input } from "#angular/core";
import { FormControl, FormGroup } from "#angular/forms";
import { Subscription } from "rxjs";
#Component({
selector: "ng-select-demo",
templateUrl: "./ng-select-demo.component.html",
styles: [
`
h1 {
font-family: Lato;
}
`
]
})
export class NgSelectDemo {
#Input() name: string;
sub = new Subscription();
originalLangCodeList = [
{ language: "" },
{ language: "en" },
{ language: "kr" },
{ language: "zh-cn" },
{ language: "ru" }
];
targetLangCodeList = [...this.originalLangCodeList];
sourceLangCodeList = [...this.originalLangCodeList];
formGroup = new FormGroup({
sourceLangCode: new FormControl(""),
targetLangCode: new FormControl("")
});
ngOnInit() {
this.sub.add(
this.formGroup.controls["sourceLangCode"].valueChanges.subscribe(
value => {
this.targetLangCodeList = this.originalLangCodeList.filter(
langObj => langObj.language !== value
);
}
)
);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
TLDR;
Use a form group to create two formControlName which you are apparently using.
In ngOnInit, subscribe the valueChanges of formGroup.controls['sourceLangCode'].
When value changes, filter the language which have been selected in targetLangCode.
In ngOnDestroy, don't forget to unsubscribe it.

How to set selected value of HTML Select Element in Angular 7 reactive forms?

I'm using Angular 7 reactive forms in my component. Part of my component:
#Component({
selector: 'my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.scss']
})
export class MyFormComponent implements OnInit {
form: FormGroup;
loaded: boolean = false;
item: Item;
// item gets loaded from the server and looks like this:
// {
// id: 'dksldfkfjdk',
// title: 'first',
// selected: 'basic'
// }
itemsForSelect = ['basic', 'primary', 'admin'];
isNew: boolean = false;
constructor(private route: ActivatedRoute,
private resourceService: ResourceService,
private fb: FormBuilder,
private router: Router) {
}
ngOnInit() {
this.resourceService.getItem().subscribe(res => {
if (res.success) {
this.item = res.item;
this.createForm();
this.loaded = true;
}
});
}
createForm() {
this.form = this.fb.group({
'title': [this.item.title, Validators.compose([])],
'selected': [this.item.selected, Validators.compose([])]
});
}
}
Part of component HTML template related form:
<form [formGroup]="form" (ngSubmit)="isNew ? create() : update()" [class.error]="!form.valid && form.touched">
<div class="form-group">
<label for="item"></label>
<select placeholder="Choose Select" [formControl]="form.controls.selected" class="form-control"
id="item">
<option *ngFor="let itemForSelect of itemsForSelect">{{ itemForSelect }}</option>
</select>
</div>
<button class="btn btn-primary udpate pointer" [disabled]="!form.valid" type="submit">
{{ isNew ? 'Create' : 'Update' }}
</button>
</form>
The problem is that after updating item with, for example admin value, it has this value from server in property selected, but it still shows basic in HTML select as selected, after fetching data and showing form. How to set selected in Angular 7? I know I can use [(ngModel)] = item.selected, but as I'm using form.controls, I'm getting warning in console.
You can use patchValue on your form control like that:
public updateValue() {
this.form.get('selected').patchValue('basic');
}
Improvement: Dont use formControl with formControlName in same form control. Here is link to deeper explanation
You need to add [value] property to options
<option
[value]="itemForSelect"
*ngFor="let itemForSelect of itemsForSelect"
>{{ itemForSelect }}</option>
Sandbox: https://codesandbox.io/s/angular-l0d09

Categories