mardi 31 juillet 2018

Angular 5 - selected option not shown on top of dropdown list

I have 3 contacts which is displayed on dropdown list and an optional value "Please select contact person" as can be seen below.

enter image description here

However, when page loads it shows the last entry in the dropdown list. Optional value "Please select contact person" should rather be shown as default initial value when page initially loads.

Component template for the dropdown list is setup as follows:

<div class="col-lg-6" *ngIf="dealer.contacts && dealer.contacts.length" >
    <label>Contact person</label><br>
    <select class="form-control" [ngModel]="survey.answer.contact.email" (ngModelChange)="onContactChange($event)">
        <option selected [ngValue]="null">Please select contact person</option>
        <option *ngFor="let contact of dealer.contacts" [ngValue]="contact.email">   , </option>
    </select>
</div>

Component class method related to the ngModelChange is as shown below. Please note that $event value is email and when it is null, an empty object is sent back - please let me know if you have comments on this as well.

onContactChange(email: any){
    if (email) {
        var contact: any = this.survey.answer.contact;
        if (contact && contact.email == email) {
            return;
        }
        this.survey.answer.contact = this.dealer.contacts.find((contact: any)=>{
            return contact.email == email;
        });
        if(this.survey.answer.emailStatus != '') {
            this.survey.answer.emailStatus = '';
        }
        this.updateSurveyContact();
    } else {
        this.survey.answer.contact = {};
    }
}




Aucun commentaire:

Enregistrer un commentaire