I am trying to create a simple select component that takes some data through attributes and displays the necessary parameters. I plan to use this select component inside the template of another component, for example, PageComponent template ( page.template.html ).
I bind the PageComponent component variable to the select component using [(ngModel)] . After choosing an option, the value of the variable will be updated as expected, but how can I set it to the first parameter when the page loads without causing manual selection in the select component?
Here is the code.
In page.template.html
<select ui-select [options]="options" [(ngModel)]="alertType" [defaultValue]="'Select an alert Type'"> </select> {{alertType}}
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; }
Currently, the {{alertType}} value is initially not displayed and is only updated when a new option is selected from the select window.
I understand that this is happening because alertType by default to undefined in PageComponent , but I canβt figure out how to set it at the first parameter value when the page loads.
Update
An initial question was given, but I had another question regarding this, so I updated the question.
In the updated code, the select component accepts the defaultValue custom property from the template and displays a conditional <option> for this default value.
Now, how can I say that if defaultValue set, alertType must have this value or else it must have the value of the first element in the options list.
PS - If you have comments about the approach used to build the component, feel free to add them to the answers, as this will help me find out.