Total Pageviews

2017/02/06

[Angular2] Dynamic Dropdown List

Problem
We have a dropdown list in the modal dialog:


The code snippet regarding dropdown list looks like:
    <div class="row">
      <div class="col-sm-10 form-inline">
        <label>電子郵件提醒事項</label>        
        <select class="form-control" id="mailNotification" [(ngModel)]="newUser.mailNotification">
            <option value="all">提醒與我的專案有關的全部事件</option>
            <option value="only_my_events">只提醒我觀察中或參與中的事物</option>
            <option value="only_assigned">只提醒我被分派的事物</option>
            <option value="only_owner">只提醒我作為擁有者的事物</option>
            <option value="none">取消提醒</option>
        </select>
      </div>
    </div>      

If I would like to use dynamic way to generate this dropdown list instead of static way, how to do it?

How-to
Step 1. declare an array which contains the texts and values in the dropdown list, and given a name 'mailNotifications'
import { Component } from '@angular/core';
import { CORE_DIRECTIVES } from '@angular/common';
import * as bootbox from 'bootbox';

@Component({
  selector: 'user-list',
  templateUrl: 'user.list.html'
})

export class UserComponent {

  searchUser: User = new User();
  newUser: User = new User();
  mailNotifications: Array<any> = [
    { text: '提醒與我的專案有關的全部事件', value: 'all' },
    { text: '只提醒我觀察中或參與中的事物', value: 'only_my_events' },
    { text: '只提醒我被分派的事物', value: 'only_assigned' },
    { text: '只提醒我作為擁有者的事物', value: 'only_owner' },
    { text: '取消提醒', value: 'none' }
  ];

  ngOnInit() {
    this.searchUser.status = 1;
  }

}



Step 2. Make good use of *ngFor to iterate its text and value for the dropdown list:
    <div class="row">
      <div class="col-sm-10 form-inline">
        <label>電子郵件提醒事項</label>
        <select class="form-control" id="mailNotification" [(ngModel)]="newUser.mailNotification">
           <option *ngFor="let n of mailNotifications" [ngValue]="n.value">{{n.text}}</option>
      </select>
      </div>
    </div>





No comments: