How can I perform click events in a select dropdown (Angular)? - html

I have two buttons (month, year) that react to different events... Now I would like to insert these events in a select. Can you please tell me how this works?
My Code:
// Solution with buttons
<button class="menu-button" type="button" mat-raised-button [ngClass]="{'active': selectedMenuLeft === 'monthButton'}" (click)="activateButton(1)">Monat</button>
<button class="menu-button" type="button" mat-raised-button [ngClass]="{'active': selectedMenuLeft === 'yearButton'}" (click)="activateButton(2)">Jahr</button>
activateButton(check) {
if (check === 1) {
this.selectedMenuLeft = 'monthButton';
this.navService.sendNavEventUpdate('month');
} else {
this.selectedMenuLeft = 'yearButton';
this.navService.sendNavEventUpdate('year');
}
}
// The same with a select. What do I have to optimize?
<select class="upload_slc" required title="">
<!-- Options -->
<option value="content" *ngFor="let navValue of menuLeftMobile" [value]="navValue">
{{ navValue }}
</option>
</select>
// Menu left in mobile
menuLeftMobile: Array<string> = ['Monat', 'Jahr'];

<mat-select placeholder="Select Menu" name="nav_value"
(selectionChange)="menuChangeAction(nav_value)"
[(ngModel)]="nav_value">
<mat-option *ngFor="let navValue of menuLeftMobile"
[value]="navValue">{{ zone.label }}</mat-option>
</mat-select>
In your component you can do the following:
nav_value: any;
menuChangeAction(value) {
console.log(value) // you will get your selected value here
}

The Simplest Way To That Is
<select #mySelect (change)='onOptionsSelected(mySelect.value)'>
And Function Will Be Like This
activateButton(check) {
if (check === "Monat") {
this.selectedMenuLeft = 'monthButton';
this.navService.sendNavEventUpdate('month');
} else {
this.selectedMenuLeft = 'yearButton';
this.navService.sendNavEventUpdate('year');
}
}
Hope This Will Work For You

You could do it by two-way binding to ngModel directive.
Controller
menuLeftMobile: Array<string> = ['Monat', 'Jahr'];
selected: string;
onChange() {
if (selected === 'Monat') {
this.selectedMenuLeft = 'monthButton';
this.navService.sendNavEventUpdate('month');
} else {
this.selectedMenuLeft = 'yearButton';
this.navService.sendNavEventUpdate('year');
}
}
Template
<select class="upload_slc" required title="" [(ngModel)]="selected" (change)="onChange()">
<!-- Options -->
<option value="content" *ngFor="let navValue of menuLeftMobile" [value]="navValue">
{{ navValue }}
</option>
</select>
Now you don't need the additional variables selectedMenuLeft to set the class. You could use the selected in the template.
<div [ngClass]="{'active': selected === 'Monat'}"></div>

Related

Get id and value from selected Dropdown

i need id and value from selected dropdown. i tried things but not getting id, only value is coming. how do i get both id and value?
below is my code
.html
<div class="form-group">
<label>Item</label>
<select id='itemCode' name="" class="form-control">
<option value="" disabled selected>Choose Item</option>
<option *ngFor="let itemValue of itemslistvalue"
[ngValue]="{id: itemValue.itemCode, name: itemValue.itemName}">
{{itemValue.itemName}}
</option>
</select>
</div>
<div class="form-group"><br>
<button type="button" (click)="add()" style=" margin-left:10px;"></button>
</div>
.TS
add() {
var itemName = (<HTMLInputElement>document.getElementById('')).value;
var itemCode = (<HTMLInputElement>document.getElementById('')).value;
if (itemName !== null && itemName !== '' && itemCode !== null && itemCode !== '') {
this.newDynamic = { itemCode: itemCode, ItemName: itemName };
console.log(this.newDynamic);
this.dynamicArray.push(this.newDynamic);
return true;
}
}
just use a variable and ngModel
//In .ts
item:any=null;
<select id='itemCode' [(ngModel)]="item" name="" class="form-control">
<!--see that by defect is [ngValue]="null"-->
<option [ngValue]="null" disabled hidden>Choose Item</option>
...
</select>
And you has stored in item the value
You can call to change if it's necesary separate the [(ngModel)]
<select id='itemCode' [ngModel]="item"
(ngModelChange)="item=$event;doSomething($event)" name="" class="form-control">
...
</select>
//in your .ts
doSomething(item:any){
console.log(item);
}
If you don't want store the variable, use a template reference
<select #itemId id='itemCode' (change)="doSomething(itemId.value)"
name="" class="form-control">
...
</select>
If you use a template reference variable, you only can get the "value" of the select (in this case only the name)
<select #itemId id='itemCode' (change)="doSomething(itemId.value)"
name="" class="form-control">
...
</select>
doSomething(item:string){
console.log(item); //<--it's only the "name"
}
a stackblitz
the referecences:
about ngModel
about template reference variables
Update if we want to add a new element to the array, we declare two variables
newItemName:string=null;
newItemCode:string=null;
And in our .html
<input [(ngModel)]="newItemName">
<input [(ngModel)]="newItemName">
<button (click)="add()">Add</button>
Before the funciton add we need take account that when we use a select with store an object. WE can take two approach
1.-use a function compare, is only write some like
compareFn(a,b){
return !a && !b ||(a && b && a.itemCode==b.itemCode)
}
//or in abreviate mode:
compareFn=(a,b)=>!a && !b ||(a && b && a.itemCode==b.itemCode)
And in .html our select like:
<select [(ngModel)]="item" .. [compareWith]="compareFn">
2.- use the own elements of the array
<option *ngFor="let itemValue of itemslistvalue"
[ngValue]="itemValue">
{{itemValue.itemName}}
</option>
But in this case we need equal to an object of an array, e.g.
item=itemslistvalue[2]
Well, our function add, can use the values of the variables. this is the significance of two-binding-way, the value of the variable is in the input, when change the input the variable change
add() {
//see that inside a function you use "this"
if (this.newItemName && this.newItemCode) {
//if only want to add value if there no selecte any thing
//replace by
// if (this.newItemName && this.newItemCode && !this.item ) {..}
//try to find one with the same code
const item = this.itemslistvalue.find(
x => x.itemCode == +this.newItemCode
);
if (!item) { //if not find
//add
this.itemslistvalue.push({
itemCode: +this.newItemCode,
itemName: this.newItemName
});
//if we want that the select gets the value added
this.item = this.itemslistvalue[this.itemslistvalue.length - 1];
} else {
this.item = item; //just equal the element found
}
}
}
.Html
<div class="form-group">
<label>Item</label>
<select id='itemCode' name="" class="form-control">
<option value="" disabled selected>Choose Item</option>
<option *ngFor="let itemValue of itemslistvalue"
[ngValue]="{{{itemValue | json}}}">
{{itemValue.itemName}}
</option>
</select>
.Ts
add() {
var itemName = (<HTMLInputElement>document.getElementById('itemCode')).value;
console.log(itemName);
let myObj = JSON.parse(itemName);
itemCode = myObj.itemCode;
itemName = myObj.itemName;}

How to enable Item on click in Angular

I have a list of subsections in my dialog container. I'm trying make all of them disabled when the dialog is open and only enabled selected subsection when the pencil icon is click for that subsection.
For example....
when user click subsection 1 pencil icon
Subsection 1 enabled
Subsection 2 disabled
Subsection 3 disabled. ....
and process will be the same for subsection 2 and 3. Any suggestion or help will be really appreciated.
<p class="substyle">Subsections</p>
<div class="substyle" *ngFor="let subsection of section.subSections">
<mat-form-field appearance="fill">
<input matInput(ngModelChange)="nameChanged({newValue: $event,
isSection: false, id: subsection.id}
[(ngModel)]="subsection.sectionName">
</mat-form-field>
<button mat-icon-button color="primary"
(click)="editDoc(subsection)"> <mat-icon>edit</mat-icon>
</button>
<button mat-icon-button (click)="openConfirmDialog(subsection, false)"
*ngIf="isSubsection"><mat-icon>delete</mat-icon>
</button>
TS
// THis is called when pencil icon is click
editDoc(value) {
this.subsectionToEdit = value;
this.refreshEditor = false;
}
// Delete Subsections
this.HelpService.deleteHelpSubsection(sec.id).subscribe(() => {
const index = this.mappedSections.findIndex((value) => value.id == sec.parentId);
if (~index) {
this.mappedSections[index].subSections = this.mappedSections[index].subSections.filter((subsection) => subsection.id != sec.id)
}
})
You can try something like this
In the input bind the [disabled] attribute to a boolean, like I have below:
<p class="substyle">Subsections</p>
<div class="substyle" *ngFor="let subsection of section.subSections">
<mat-form-field appearance="fill">
<input [disabled] = "subsection.id !== selectedId" matInput style="width: 200px; height: 15px;" type="text"
(ngModelChange)="nameChanged({newValue: $event, isSection: false, id: subsection.id})"
[(ngModel)]="subsection.sectionName">
</mat-form-field>
<button mat-icon-button color="primary" matTooltip="Edit documents for this Subsection"
style="bottom: 10px;" (click)="editDoc(subsection)"> <mat-icon>edit</mat-icon>
</button>
<button mat-icon-button color="primary" matTooltip="Delete this
Subsection" (click)="openConfirmDialog(subsection, false)"
style="bottom: 10px;" *ngIf="isSubsection"><mat-icon>delete</mat-icon>
</button>
Then in your editDoc function, do the following:
editDoc(value) {
// make sure you make selectedId a property before doing this
this.selectedId = value.id // set the selectedId property to the selected value id
this.subsectionToEdit = value;
this.refreshEditor = false;
}
So what will happen is, whenever the selectedId is set, it will set all the inputs that don't belong to the selected subsection to disable automatically.

Angular Load new Autocomplete values on each select change event

I have several most important fields in my form. In first form, user should choose the company by mat-select-search. After that, by using (selectionChange) I'm calling API with selected value in the first field( this is company id) and return users from that company to autocomplete for recipient fields. It works perfectly, if user does not change his chosen company. But if he do that (selectionChange) method doesn't reload autocomplete with new value. There is a situation in which the user has another company selected, and autocomplete remains from the previous one. Event only loads new one if the previous output was empty.
Is it possible to change this behavior? May be it,s possible to delete previous results from api calling?
My form :
<form [formGroup]="orderForm" novalidate (ngSubmit)="createOrder()">
<div class="row">
<div class="col-md-12">
<mat-form-field class="example-full-width" formGroupName='Company'>
<mat-select ngDefaultControl placeholder="Company" #singleSelect formControlName="id" (openedChange)="onSelectionChange($event)" [(value)]="selectedVariable">
<mat-option>
<ngx-mat-select-search [formControl]="companySelectFilter" [searching]="searching" placeholderLabel="Find company..." noEntriesFoundLabel="'no matching companies found'" ></ngx-mat-select-search>
</mat-option>
<mat-option *ngFor="let company of filteredCompanies | async" [value]="company.id">
{{company.company_name| titlecase}} {{company.company_address| titlecase}}
</mat-option>
</mat-select>
<mat-error *ngIf="orderForm.hasError('notSame')">
Recipient has another company! Select again.
</mat-error>
</mat-form-field>
</div>
</div>
<div class="row" matAutocompleteOrigin #origin="matAutocompleteOrigin">
<div class="col-md-6">
<mat-form-field class="example-full-width" formGroupName='recipient' >
<input type="text"
matInput
formControlName="user_name"
placeholder="First Name"
[matAutocomplete]="auto"
[matAutocompleteConnectedTo]="origin">
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="setFormData($event)">
<mat-option *ngFor="let recipient of filteredOptions | async" [value]="recipient">
<div style="display:flex;flex-wrap: nowrap;align-items:center;justify-content:center;margin: auto;">
<span style="flex-grow: 1;flex: 1 1 33%;"> {{recipient.user_name.toString() | titlecase}} {{recipient.user_surname.toString() | titlecase}} {{recipient.company.company_name.toString() | titlecase}}
</span>
</div>
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
<div class="col-md-6" >
<mat-form-field class="example-full-width" formGroupName='recipient'>
<input matInput formControlName="user_surname" placeholder="Last Name"[matAutocomplete]="auto"
[matAutocompleteConnectedTo]="origin" >
<mat-error *ngIf="orderForm.get('recipient.user_surname').hasError('required')">
Last Name is <strong>required</strong>
</mat-error>
</mat-form-field>
</div>
</div>
<div class="col-md-6" >
<mat-form-field class="example-full-width" formGroupName='recipient'>
<input matInput placeholder="Mobile Phone" type="text" formControlName="user_telephone" >
</mat-form-field>
</div>
OnSelected change method:
onSelectionChange(opened: boolean) {
console.log(`opened is : ${opened}`);
if (!opened && this.selectedVariable) {
this.orderForm.get('recipient.user_name').reset()
this.orderForm.get('recipient.user_surname').reset()
this.orderForm.get('recipient.user_telephone').reset()
this.filteredOptions = this.orderForm
.get('recipient.user_name')
.valueChanges.pipe(
startWith(""),
debounceTime(400),
distinctUntilChanged(),
switchMap((val) => {
return this.doFilter(this.selectedVariable, val || '');
})
);
}
}
And doFilter method :
doFilter(id: number, val: any): Observable<any[]> {
return this.recipientService.getRecipientsByCompany(id).pipe(
map((response) =>
response.filter((option) => {
return (
option.user_name
.toString()
.toLowerCase()
.indexOf(val.toString().toLowerCase()) === 0 ||
option.user_surname
.toString()
.toLowerCase()
.indexOf(val.toString().toLowerCase()) === 0
);
})
)
);
}
Finally, I found a solution. My mistake was I trying to retrieve the data from API after page loaded. Now, I load all the recipients in NgOnInit method and filter the data after user change the company.
LoadRecipients method which we put into ngOnInit:
this.recipientService
.getRecipientsObs()
.subscribe((recipients) => (this.recipients = recipients));
}
And new OnChange method :
selectedVariable: any;
onSelectionChange(opened: boolean) {
console.log(`opened is : ${opened}`);
console.log(this.selectedVariable)
if (!opened && this.selectedVariable) {
this.orderForm.get("recipient.user_name").reset();
this.orderForm.get("recipient.user_surname").reset();
this.orderForm.get("recipient.user_telephone").reset();
const formsInput = merge(
this.orderForm.get('recipient.user_name').valueChanges,
this.orderForm.get('recipient.user_surname').valueChanges
);
formsInput.pipe(
startWith(""),
debounceTime(400),
distinctUntilChanged(),
map((search) => {
if (!this.recipients) {
return [];
} else {
search = search.toLowerCase();
}
return this.recipients.filter(
(recipient) =>
recipient.company.id === this.selectedVariable &&
recipient.user_name.toLowerCase().indexOf(search) > -1 &&
recipient.user_surname.toLowerCase().indexOf(search) > -1
);
}),
delay(500)
)
.subscribe(
(filteredRecipients) => {
this.searching = false;
this.filteredRecipients.next(filteredRecipients);
},
(error) => {
this.searching = false;
}
);
}
}

how to get value from checkbox when clicked and show it on top of from before submited

I need show my checkbox value when it clicked and show it on top with chips before submited. My checkbox use service for showing the data
I already make a clicked function in my checkbox tag, but its not get the value until i clicked it twice.
my html:
<mat-chip-list #chipList>
<mat-chip color="primary" *ngIf="ars != null" selected>
{{ars}}
<mat-icon matChipRemove (click)="remove(dataForm)">cancel</mat-icon>
</mat-chip>
</mat-chip-list>
</div>
<mat-form-field class="search">
<mat-icon matPrefix>search</mat-icon>
<input
fromControlName="firstName"
type="search"
matInput
placeholder="Search"
/>
</mat-form-field>
<section>
<mat-checkbox value="0" class="" [(ngModel)]="checked" (click)="checkAll">
select all
</mat-checkbox>
</section>
<div *ngFor="let data of formData">
<mat-checkbox [(ngModel)]="data.isSelected"
(click)="submit(formData)"> {{ data.name }} </mat-checkbox>
</div>
my ts file:
this my function for get the value
submit(a) {
for (let i = 0; i < a.length; i++) {
if (a[i].isSelected === true) {
//this.status = this.status + (JSON.stringify(a[i])) ;
// this.arr = [this.status];
this.arr = Object.values(a[i]);
this.ars = this.arr[0];
//this.arr, Validators.required;
}
}
console.log('test for submit', this.ars);
}
I expect the value showing right after clicked, but the value show after the checkbox clicked twice

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>