Angular deselect all options in multiple select - html

Goal is that, when I call myMethod(), I want to have all options unselected.
Currently when I call myMethod() it will deselect only the last option, but the other remain selected if they have been selected.
Solutions:
Not using reactive forms - do it like in the accepted answer
Using reactive forms - this.formName.get('formControlName').setValue([]);
HTML
<select multiple>
<option *ngFor="let user of users"
value="{{user.id}}"
[selected]="usersSelected">{{user.name}}
</option>
</select>
Component
usersSelected: boolean = false;
myMethod(): void {
this.usersSelected = false;
}
Thanks for any help.

You should use [(ngModel)] so you can control the value. Note that its multiple select, so you should use array, not just scalar value.
usersSelected = [];
myMethod(): void {
this.usersSelected = [];
}
And in your template:
<select multiple [(ngModel)]="usersSelected">
<option *ngFor="let user of users" [ngValue]="user.id">{{user.name}}</option>
</select>
Working example: https://stackblitz.com/edit/angular-c9y1jm

Related

how can I know which option is clicked on in a select tag while updating a variable in the ts file?

I have this simple select that is generating the numbers from an array in the component.ts file and I want to make it so that when the user clicks a number on the dropdown list, a variable in that .ts file is updated (inputBoxes) and that many input boxes will be displayed.
in my html file I have
component.html
<p>How many words will you be using?</p>
<select>
<option *ngFor="let num of wordCount" (click)="updateInputBoxes(num)">{{num}}</option>
</select>
component.ts
public wordCount: Array<number> = [1,2,3,4,5];
public inputBoxes: number;
constructor() { }
ngOnInit(): void {
}
updateInputBoxes(num: number) {
this.inputBoxes = num;
}
This is what I was trying so far but the updateInputBoxes function doesn't even execute. How do I know which number is selected while sending that selected number as a parameter to the function updateInputBoxes?
You need to add change method in select tag then pass the event to get current selected option vaule in ts file.
Try this code to get selected option value :
HTML CODE
<select (change)="updateInputBoxes($event)">
<option value="">
Select count
</option>
<option *ngFor="let num of wordCount" value={{num}}>{{num}}</option>
</select>
TS CODE
updateInputBoxes(event) {
this.inputBoxes = event.target.value;
}
If you want to call method after select each options you need to use change event in select tag not option tag.
And to pass selected value to your methods you can use template reference like this:
<select #selectList (change)="updateInputBoxes(selectList.value)">
<option *ngFor="let num of wordCount" [value]="num">{{num}}</option>
</select>
Here is working sample I created: StackBlitzLink
But if you only need selected value of selectbox there is no need to call fanction just use [(ngModel)]="inputBoxes" like this:
<select [(ngModel)]="inputBoxes">
<option *ngFor="let num of wordCount" [value]="num">{{num}}</option>
</select>
Use template driven or reactive forms for this.
The template driven version looks like this:
<select name="countControl" [(ngModel)]="inputBoxes">
<option *ngFor="let wordCount of wordCounts" [ngValue]="wordCount">
{{ wordCount }}
</option>
</select>
Docs: https://angular.io/api/forms/SelectControlValueAccessor#description

How do I reset select and ng-select to first option dynamically

UPDATE ::
https://stackblitz.com/edit/angular-ivy-tggo2e?file=src%2Fapp%2Fapp.component.ts
This stack is basically a TLDR of this post.
UPDATE 2::
Ok basically in that blitz, example 2 works. haha. in my code I was resetting that arr2 in my subscribe after the API call but doing it before the API call fixed it. Now I just have to figure out how to give it that first option (Pick something..) on initial load instead of a blank box.
///////////////////
So basically I have a cascade of select dropdowns. Lets call them form1, form2, form3.
When I select form1, it will call an API using that selection and dynamically give me an array to use for form2 options. same for form3,4,5,etc.
Now this is no problem up to here. But when I have selected form1,2,3 and then I select form1 again, I want form 2 and 3 to reset to my disabled option 1 but I can't seem to be able to get that to happen.
Component.ts
dropdownForm() {
this.dropdownForm = new FormGroup({
form1: new FormControl(),
form2: new FormControl(),
form3: new FormControl(),
form4: new FormControl()
)}
callAPI(query) {
// API CALL
}
changeONE(e) {
// this.arr2 = [];
// reset this.dropdownForm.form2 back to the first option 1('Pick something..) to be 'selected' and 'disabled'
// this.callAPI(e)
}
changeTWO(e) {
// this.arr3 = []
// reset this.dropdownForm.form3
this.callAPI(e)
}
changeTHREE(e) {
// this.arr4 = []
// reset this.dropdownForm.form4 -- this one is ng-select so it is way different than the others.
// this.callAPI(e)
}
HTML
<form [formGroup]="dropdownForm">
<div>
<div>
<label for="form1">Form1</label>
<select id="form1"
(change)="changeONE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr">{{item}}</option>
</select>
</div>
<div>
<label for="form2">Form2</label>
<select id="form2"
(change)="changeTWO($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr2">{{item}}</option>
</select>
</div>
<div>
<label for="form3">Form3</label>
<select id="form3"
(change)="changeTHREE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr3">{{item}}</option>
</select>
</div>
<div>
<label for="form4">Form4:</label>
<ng-select [multiple]="true" placeholder="Pick something" (change)="changeFOUR($event)" >
<ng-option *ngFor="let item of arr4">{{item}}</ng-option>
</ng-select>
</div>
I've tried adding formControlname in my selects but that makes the select act weird for some reason... maybe its because my 'new FormControl('')' is wrong? But it makes my form1,2,3 just preselect something random in my optionsArr.
And even then, if i do this.dropdownForm.controls.form1.reset() or something like that, it doesn't do anything. it will just reset the value instead of the resetting the dropdown box(which I'm not even using anyways.. haha. I should be but I'm using using that changeONE() and $event to get the value)
Thank you
EDIT::
I just tried
component.ts
this.dropdownForm.get('form2').reset()
HTML
<select id="form1"
(change)="changeONE($event)" formControlName='form1'>
And basically when I have form1 and form2 selected and I go back and select form1 with that this.dropdownForm.get('form2').reset(), it won't reset form2. Instead, it will select the first item in the new updated arr2 (after i get arr2 from that API call) on the second option of that select instead of going to that disabled option one.

How can I change the index of array using angular 6?

I have this array in my typescript. I'm using angular 6.
formats: any = ['Years/Months/Days', 'Years/Months/Week', 'Months/Days', 'Week/Days', 'Week/Half Days', 'Week/4 Hours', 'Week/Hours', 'Days/Hours/30Min', 'Days/Hours/15Min'];
and this is my html code.
<select class="form-control" formControlName="format">
<option [ngValue]="null">{{'Select Type' | translate}}</option>
<option *ngFor="let format of formats" [ngValue]="format">{{format}}</option>
</select>
I want to change the dropdown value with help of next and prevoius button.
I recommend you to have a variable for storing the index of the selected option and initialize it to zero, every time the selected value gets changed update the index.
then you can create two buttons for next and previous with click event mapped to both buttons
the .ts file and function might look something like this
selectedindex:any = 0;
changed(event : Event):any{
console.log(event)
if( event.target){
console.log( this.formats.indexOf(this.yourformobject.controls['format'].value))
this.selectedindex = this.formats.indexOf(this.yourformobject.controls['format'].value;
}
}
next():any{
if(this.selectedindex < this.formats.length-1){
this.selectedindex++;
this.yourformobject.controls['format'].setValue(this.formats[this.selectedindex]);
}
}
previous():any{
if(this.selectedindex>0){
this.selectedindex--;
this.yourformobject.controls['format'].setValue(this.formats[this.selectedindex]);
}
}
and the Html look like this
<form [formGroup]="yourformobject">
<select class="form-control" formControlName="format" (click)="changed($event)">
<option [ngValue]="null">Select Type</option>
<option *ngFor="let format of formats" [ngValue]="format">{{format}}</option>
</select>
<button (click)="next()">next</button>
<button (click)="previous()">previous</button>
</form>

Angular 2 Dropdown Options Default Value

In Angular 1 I could select the default option for a drop down box using the following:
<select
data-ng-model="carSelection"
data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>
In Angular 2 I have:
<select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
How could I select a default option given my option data is:
[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?
Add a binding to the selected property, like this:
<option *ngFor="#workout of workouts"
[selected]="workout.name == 'back'">{{workout.name}}</option>
If you assign the default value to selectedWorkout and use [ngValue] (which allows to use objects as value - otherwise only string is supported) then it should just do what you want:
<select class="form-control" name="sel"
[(ngModel)]="selectedWorkout"
(ngModelChange)="updateWorkout($event)">
<option *ngFor="let workout of workouts" [ngValue]="workout">
{{workout.name}}
</option>
</select>
Ensure that the value you assign to selectedWorkout is the same instance than the one used in workouts. Another object instance even with the same properties and values won't be recognized. Only object identity is checked.
update
Angular added support for compareWith, that makes it easier to set the default value when [ngValue] is used (for object values)
From the docs https://angular.io/api/forms/SelectControlValueAccessor
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
This way a different (new) object instance can be set as default value and compareFn is used to figure out if they should be considered equal (for example if the id property is the same.
Add this Code at o position of the select list.
<option [ngValue]="undefined" selected>Select</option>
just set the value of the model to the default you want like this:
selectedWorkout = 'back'
I created a fork of #Douglas' plnkr here to demonstrate the various ways to get the desired behavior in angular2.
You Can approach this way:
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
or this way:
<option *ngFor="let workout of workouts" [attr.value]="workout.name" [attr.selected]="workout.name == 'leg' ? true : null">{{workout.name}}</option>
or you can set default value this way:
<option [value]="null">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
or
<option [value]="0">Please Select</option>
<option *ngFor="let workout of workouts" [value]="workout.name">{{workout.name}}</option>
Use index to show the first value as default
<option *ngFor="let workout of workouts; #i = index" [selected]="i == 0">{{workout.name}}</option>
According to https://angular.io/api/forms/SelectControlValueAccessor you
just need the following:
theView.html:
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
theComponent.ts
import { SelectControlValueAccessor } from '#angular/forms';
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.
HTML template:
<select (change)="onValueChanged($event.target)">
<option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">{{option.text}}</option>
</select>
Component:
import { Component, Input, Output, EventEmitter, OnInit } from '#angular/core';
export class UifDropdownComponent implements OnInit {
#Input() uifOptions: {value: string, text: string}[];
#Input() uifSelectedValue: string = '';
#Output() uifSelectedValueChange:EventEmitter<string> = new EventEmitter<string>();
uifSelected: {value: string, text: string} = {'value':'', 'text':''};
constructor() { }
onValueChanged(target: HTMLSelectElement):void {
this.uifSelectedValue = target.value;
this.uifSelectedValueChange.emit(this.uifSelectedValue);
}
ngOnInit() {
this.uifSelected = this.uifOptions.filter(o => o.value ==
this.uifSelectedValue)[0];
}
}
Fully fleshing out other posts, here is what works in Angular2 quickstart,
To set the DOM default: along with *ngFor, use a conditional statement in the <option>'s selected attribute.
To set the Control's default: use its constructor argument. Otherwise before an onchange when the user re-selects an option, which sets the control's value with the selected option's value attribute, the control value will be null.
script:
import {ControlGroup,Control} from '#angular/common';
...
export class MyComponent{
myForm: ControlGroup;
myArray: Array<Object> = [obj1,obj2,obj3];
myDefault: Object = myArray[1]; //or obj2
ngOnInit(){ //override
this.myForm = new ControlGroup({'myDropdown': new Control(this.myDefault)});
}
myOnSubmit(){
console.log(this.myForm.value.myDropdown); //returns the control's value
}
}
markup:
<form [ngFormModel]="myForm" (ngSubmit)="myOnSubmit()">
<select ngControl="myDropdown">
<option *ngFor="let eachObj of myArray" selected="eachObj==={{myDefault}}"
value="{{eachObj}}">{{eachObj.myText}}</option>
</select>
<br>
<button type="submit">Save</button>
</form>
You can Use that [ngModel] instead of [(ngModel)]and it is Ok
<select class="form-control" **[ngModel]="selectedWorkout"** (ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
You can do as above:
<select class="form-control"
[(ngModel)]="selectedWorkout"
(ngModelChange)="updateWorkout($event)">
<option *ngFor="#workout of workouts;
let itemIndex = index"
[attr.selected]="itemIndex == 0">
{{workout.name}}
</option>
</select>
In above code as you can see, selected attribute of the repeating option is set on checking index of the repeating loop of list. [attr.< html attribute name >] is used for setting html attribute in angular2.
Another approach will be setting model value in typescript file as :
this.selectedWorkout = this.workouts.length > 0
? this.workouts[0].name
: 'No data found';//'arm'
Add on to #Matthijs 's answer, please make sure your select element has a name attribute and its name is unique in your html template. Angular 2 is using input name to update changes. Thus, if there are duplicated names or there is no name attached to input element, the binding will fail.
I faced the same problem while using angular 11. But finally found a solution.
<option disabled selected value="undefined">Select an Option</option>
complete example with ngFor.
<select name="types" id="types" [(ngModel)]="model.type" #type="ngModel">
<option class="" disabled selected value="undefined">Select an Option</option>
<option *ngFor="let item of course_types; let x = index" [ngValue]="type.id">
{{ item.name }} </option>
</select>
Add binding property selected, but make sure to make it null, for other fields e.g:
<option *ngFor="#workout of workouts" [selected]="workout.name =='back' ? true: null">{{workout.name}}</option>
Now it will work
<select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
<option value="{{workout.name}}" *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
If you are using form there should be name field inside select tag.
All you need to do is just add value to the option tag.
selectedWorkout value should be "back" , and its done.
If you don't want the 2-way binding via [(ngModel)], do this:
<select (change)="selectedAccountName = $event.target.value">
<option *ngFor="let acct of accountsList" [ngValue]="acct">{{ acct.name }}</option>
</select>
Just tested on my project on Angular 4 and it works! The accountsList is an array of Account objects in which name is a property of Account.
Interesting observation:
[ngValue]="acct" exerts the same result as [ngValue]="acct.name".
Don't know how Angular 4 accomplish it!
Step: 1 Create Properties declare class
export class Task {
title: string;
priority: Array<any>;
comment: string;
constructor() {
this.title = '';
this.priority = [];
this.comment = '';
}
}
Stem: 2 Your Component Class
import { Task } from './task';
export class TaskComponent implements OnInit {
priorityList: Array<any> = [
{ value: 0, label: '✪' },
{ value: 1, label: '★' },
{ value: 2, label: '★★' },
{ value: 3, label: '★★★' },
{ value: 4, label: '★★★★' },
{ value: 5, label: '★★★★★' }
];
taskModel: Task = new Task();
constructor(private taskService: TaskService) { }
ngOnInit() {
this.taskModel.priority = [3]; // index number
}
}
Step: 3 View File .html
<select class="form-control" name="priority" [(ngModel)]="taskModel.priority" required>
<option *ngFor="let list of priorityList" [value]="list.value">
{{list.label}}
</option>
</select>
Output:
You just need to put the ngModel and the value you want selected:
<select id="typeUser" ngModel="Advanced" name="typeUser">
<option>Basic</option>
<option>Advanced</option>
<option>Pro</option>
</select>
For me, I define some properties:
disabledFirstOption = true;
get isIEOrEdge(): boolean {
return /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)
}
Then in the constructor and ngOnInit
constructor() {
this.disabledFirstOption = false;
}
ngOnInit() {
setTimeout(() => {
this.disabledFirstOption = true;
});
}
And in the template I add this as the first option inside the select element
<option *ngIf="isIEOrEdge" [value]="undefined" [disabled]="disabledFirstOption" selected></option>
If you allow to select the first option you can just remove the usage of the property disabledFirstOption
In my case, here this.selectedtestSubmitResultView is set with default value based on conditions and an variable testSubmitResultView must be one and same as testSubmitResultView. This indeed worked for me
<select class="form-control" name="testSubmitResultView" [(ngModel)]="selectedtestSubmitResultView" (ngModelChange)="updatetestSubmitResultView($event)">
<option *ngFor="let testSubmitResultView of testSubmitResultViewArry" [ngValue]="testSubmitResultView" >
{{testSubmitResultView.testSubmitResultViewName}}
</option>
</select>
For More Information,
testSubmitResultViewArry: Array<any> = [];
selectedtestSubmitResultView: string;
getTestSubmitResultViewList() {
try {
this.examService.getTestSubmitResultViewDetails().subscribe(response => {
if (response != null && response !== undefined && response.length > 0) {
response.forEach(x => {
if (x.isDeleted === false) {
this.testSubmitResultViewArry.push(x);
}
if (x.isDefault === true) {
this.selectedtestSubmitResultView = x;
}
})
}
});
} catch (ex) {
console.log('Method: getTestSubmitResultViewList' + ex.message);
}
}
I faced this Issue before and I fixed it with vary simple workaround way
For your Component.html
<select class="form-control" ngValue="op1" (change)="gotit($event.target.value)">
<option *ngFor="let workout of workouts" value="{{workout.name}}" name="op1" >{{workout.name}}</option>
</select>
Then in your component.ts you can detect the selected option by
gotit(name:string) {
//Use it from hare
console.log(name);
}
works great as seen below:
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>

Chosen select not calling a function on ng-click

I'm working with a chosen select, i added a function call when the event ng-click happens, but it's not doing anything, when i make the call to the same function in a button it works, why is this?
ng-change doesn't work either, even worse, it eats my options and leaves only the first one.
my select code:
<select ng-model="ind_oferta" multiple class="control-group chosen-select" chosen >
<optgroup label="Oferta">
<option value=""> </option>
<option ng-click="aplicarFiltro()" ng-repeat="menuOpcion in menu[0].opciones.oferta" value={{menuOpcion.id}}>
{{menuOpcion.tipo}}</option>
</optgroup>
</select>
the function is very simple, it's just a javascript alert
$scope.aplicarFiltro = function(){
alert("hello");
}
and i think is not worth put the button code, that one works so...
EDIT: i changed the select code to this, still not making the call to the function, help!
<select multiple class="control-group chosen-select" chosen style="width:250px;"
ng-model="ind_oferta" ng-click="aplicarFiltro();"
ng-options="menuOpcion.id as menuOpcion.tipo for menuOpcion in menu[0].opciones.oferta">
<option>--</option>
</select>
You should use the ng-options directive together with ng-model (you can still add a single <option> as the default value). It would probably look something like this:
<select ng-options="menuOpcion.tipo for menuOpcion in menu[0].opciones.oferta"
ng-model="selected"
ng-change="aplicarFiltro()" chosen multiple>
<option value=""></option>
</select>
There is a lot of customization options, so it is best if you check out the documentation.
To get the option which was removed by the user you could do something like this in your controller:
var previousSelection = [];
$scope.changedSelection = function () {
// Check if the current selection contains every element of the previous selection
for (var i = 0; i < previousSelection.length; i++) {
if ($scope.selectModel.indexOf(previousSelection[i]) == -1) {
// previousSelection[i] was deselected
}
}
// Set the previous selection to the current selection
previousSelection = $scope.selectModel;
}