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

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>

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 to call an angular function within another function?

I have three select options in my html page. Based on the three selecting values I need to write a value in another text box.
<select (change)="aaFilter($event.target.value)" class="form-control">
<option *ngFor="let type of aa" [value]="type.value">
{{type.display}}
</option>
</select>
<select (change)="bbFilter($event.target.value)" class="form-control">
<option *ngFor="let type of bb" [value]="type.value">
{{type.display}}
</option>
</select>
<select (change)="ccFilter($event.target.value)" class="form-control">
<option *ngFor="let type of cc" [value]="type.value">
{{type.display}}
</option>
</select>
So I have Onchange function in every select box. Now In my typescript file my
aaFilter(selectedaa:string){
console.log('value is ',selectedaa);
}
Likewise I have written three functions. But based on this values I need to set up a value in textbox.
headerName(){
//Here I need to take up the threee selected values from drop down & do some function based on that.
}
How can that be done in angular 6 & typescript?
In component:
Public selectedValues = [];
aaFilter(value, index){
this.selectedValues[index] = value;
this.updateModelInput();
}
bbFilter(value, index){
this.selectedValues[index] = value;
this.updateModelInput();
}
ccFilter(value, index){
this.selectedValues[index] = value;
this.updateModelInput();
}
updateModelInput(){
if(this.selectedValues.length === 3){
// UPDATE THE VALUE IN TEXT BOX
}
}
From Template, you can pass value 0, 1, 2 as 2nd parameter in change method.
Well, you haven't bound anything to the select options have you?
<select
[(ngModel)] ="filterA"
(change) ="headerName()"
class ="form-control">
<option *ngFor="let type of aa" [value]="type.value">
{{type.display}}
</option>
</select>
<select
[(ngModel)] ="filterB"
(change) ="headerName()"
class ="form-control">
<option *ngFor ="let type of bb" [value]="type.value">
{{type.display}}
</option>
</select>
<select
[(ngModel)] ="filterC"
(change) ="headerName()"
class ="form-control">
<option *ngFor="let type of cc" [value]="type.value">
{{type.display}}
</option>
</select>
In your component file:
headerName()
{
/* Do whatever this function is supposed to do whenever one of the
filters is changed. The variables filterA, filterB and filterC will
now always have the most recent values for you to operate on */
}

How to have a default "please select" option on an Angular select element with a null value for validation?

I have a select HTML element in an Angular ngFor loop:
<select formControlName="type" required>
<option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option>
</select>
In Internet Explorer, the first item in the list is selected when the template loads, but it's value isn't set in the form control, so causes a 'required' validation error until another value is selected in the list. I want to have a 'Please select' option that has a null value to prevent this happening.
This is for Angular 2+ used with or without TypeScript
Add an option like so:
<option [ngValue]="null">Please select</option>
So your control will look like:
<select formControlName="type" required>
<option [ngValue]="null">Please select</option>
<option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option>
</select>
This works as Angular inspects the value attribute because of the square brackets. The value becomes a true null, unlike if we used value="" (this is just an empty string and doesn't match null).
In case you're not using ngForm, another approach to implementing the selected value is to do something like [value]='selectedType' (change)='selectedType = $event.target.value' in your select tag. For example:
In your component.ts:
public selectedType: string;
In your component.html
<select [value]='selectedType' (change)='selectedType = $event.target.value'>
<option value=''>-- Select your Type --</option>
<option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option>
</select>
component.ts
public selectedValue = 'None';
component.html:
<div ">
<label>Highlight</label>
<select [(ngModel)]="selectedTrunk" (change)="onChangeTrunk($event)">
<option value='None'>None</option>
<option *ngFor="let trunklist of DRLNameTrunkList" [selected]="trunk" [value]="trunklist.SIPTRUNKNAME">{{trunklist.SIPTRUNKNAME}}</option>
</select>
</div>
This is my code pelase modify as per your requirements

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;
}