I am trying to create a simple select
component which takes in some data via attributes and renders the required options. I plan to use this select component inside the template of another component, say PageComponent
's template( page.template.html ).
I am binding a variable of PageComponent to the select
component using [(ngModel)]
. Upon selecting an option, the value of the variable get's updated as expected but how do I set it to point to the first option upon page load without triggering a manual selection on the select
component?
Here's the code.
In page.template.html
<select ui-select
[options]="options"
[(ngModel)]="alertType"
[defaultValue]="'Select an alert Type'">
</select>
{{alertType}} <!-- To see the value while debugging -->
In page.component.ts, PageComponent
class
alertType:any;
options = [
{id:1, value:"item-1"},
{id:2, value:"item-2"},
{id:3, value:"item-3"}
];
In select.component.ts
import {Component, Input} from '@angular/core'
@Component({
selector: '[ui-select]',
template: `
<option *ngIf="defaultValue" value="-1">{{defaultValue}}</option>
<option *ngFor="let option of options" [value]="option.id">{{option.value}}</option>
`
})
export class SelectComponent {
@Input() options: any;
@Input() defaultValue: string;
}
Right now, the {{alertType}}
value initially shows nothing and updates only upon selecting a new option from the select
box.
I do understand that it's happening because alertType
is set to undefined by default in PageComponent
but I can't figure out how to set it to the first option value when the page loads.
Update
The original question has been answered but I had one more question regarding this so updated the question.
In the updated code, the select
component accepts a defaultValue
custom property from the template and renders a conditional <option>
for that default value.
Now, how do I say that if defaultValue
is set, alertType
should have that value or otherwise it should have the value of the first item in the options
list.