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

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.

Related

How to set Vue Core UI select value

Sorry for the beginner question, I am new to Vue.js. I am using CoreUI. Documentation/Tutorials on CoreUI+Vue are scarce.
I am using the <CForm> tag and here I have a <CSelect> tag.
<CForm #submit="test" ref="form">
<CSelect
label="Pick a name"
:options="['test', 'test1', 'test2']"
v-model="testy"
/>
<CButton type="submit" size="sm" color="primary"> Submit</CButton>
</CForm>
JavaScript:
methods: {
test(e) {
console.log("test");
debugger;
e.preventDefault();
}
}
When my breakpoint is hit and I inspect this.testy it will not return the value of the select box but instead this:
I was under the impression that putting v-model on my CSelect will expose my select box under this.* and I could somehow easily get the value (?!).
For context this is rendered in the DOM:
<select id="uid-wvkj98yh6gp" class="form-control">
<option data-key="0" value="test"> test </option>
<option data-key="1" value="test1"> test1 </option>
<option data-key="2" value="test2"> test2 </option>
</select>
My question: inside my test(e) method, how can I gather the current selected value of my select box?
In the <CSelect> API docs, it lists the value prop:
value
The value of select input. Set .sync modifier to track prop changes.
It seems they don't use v-model as expected and you probably also got an error about the value prop being incorrect.
Change your select to:
<CSelect
label="Pick a name"
:options="['test', 'test1', 'test2']"
:value.sync="testy"
/>
This way you use the .sync modifier the way the guide directs.

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 5 ngModel changes the value in UI without saving it

In my form I have a select with a bind variable. If I try to change and save the value it works fine but if I try to change the value in my modal and instead of save it, I close the modal (so I do not save the value) in my UI I see the changed value and obviously in my DB the value is not changed.
component.html
<select class="form-control m-input" id="type" formControlName="type"
[ngClass]="{ 'is-invalid': submitted && formcontrols.type.errors }" name="type"
(change)="changeType($event, newParameter.type)"
[(ngModel)]="newParameter.type">
<option [ngValue]="'STRUCT'">STRUCT</option>
<option [ngValue]="'NUM'">NUM</option>
<option [ngValue]="'BOOLEAN'">BOOLEAN</option>
<option [ngValue]="'DATE'">DATE</option>
</select>
component.ts
changeType(event, type){
type= this.createParameterForm.get('type').value;
if(type==="NUM"){
this.initNUMControlsForm();
}
else if(type ==="STRUCT"){
this.initStructControlsForm();
}
else{
this.initControlsForm();
}
}
How can I avoid this problem?
usually you need to create another instance of your object at beginning and modify that object by your form. You can create the new object by const newObj = {...originalObj} or const newObj = JSON.parse(JSON.stringify(originalObj))
if user tries to save, pass the new object to save function and after success save, copy it back to original object
if user cancels, do nothing because your original object is not changed

How to save the selected select option drop-down once webpage has loaded

I need some help with this HTML code I'm trying to improve.
I don't have much HTML knowledge so the most basic solution would be nice.
Currently, the code works fine but I want once the page has loaded for the drop-down option to be that of the selected option that I click Submit with. Same with the slider, if I select 2, I want 2 to be displayed on the new page once loaded.
Is there a way to do this with variables or how?
<div id="input_header">
<div id="logo_div">
<img id="logo" src="static/steering-wheel.svg">
<p id="logo_name">TITLE</p>
</div>
<form id="driver_form" action="compare_driver" method="get">
<p class="label">Vendor:</p>
<select class="driver_input_box" name="driver_vendor">
<option value="Vendor A">AAA</option>
<option value="Vendor B">BBB</option>
<option value="Vendor C">CCC</option>
</select>
<p class="label"># to show: </p>
<div id="count_slider">
<input id="driver_count_id" name="driver_count" type="range" min="1" max="10" step="1" value="5" oninput="driver_count_out_id.value = driver_count_id.value"/>
<output id="driver_count_out_id" name="driver_count_output" >5</output>
</div>
<input id="compare_driver" type="submit" value="Compare">
</form>
</div>
First you need to include some JavaScript there. The easiest (but probably worse) way is to add an script tag to the HTML.
To get the selected option with Javascript, you can check these answers: Get selected value in dropdown list using JavaScript? . The code will be easier to write if you give an id to your <select>, like: <select id="mySelect" class="driver_inpu....
<script>
//check if there's an old selection by the user:
if (sessionStorage.getItem("selectedOption")) {
//to set the selected value:
document.getElementById("mySelect").value = sessionStorage.getItem("selectedOption");
}
//this will set the value to sessionStorage only when user clicks submit
document.getElementById("driver_form").addEventListener("submit", () => {
//to get the selected value:
var selectedOption = document.getElementById("mySelect").value;
sessionStorage.setItem("selectedOption", selectedOption);
});
/*
//use this only if you want to store a new value
//every time the user clicks on another option
document.getElementById("mySelect").addEventListener("change", () => {
//to get the selected value:
var selectedOption = document.getElementById("mySelect").value;
sessionStorage.setItem("selectedOption", selectedOption);
});
*/
</script>
You can put it in window.onload if you want to. This answer should put you in the right track. I'm very tired and I haven't tested it, but it should work.

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