Angularjs2-下拉列表實現(父子組件通訊)

基於http://valor-software.com/ng2-bootstrap/#/dropdowns 作的一個下拉列表控件,優化了以下功能,項目地址javascript

  • 列表內容由父組件傳遞
  • 子組件選擇框發生變化後會通知父組件

demo

demo-new.gif

列表內容由父組件傳遞

這個主要利用到了ng2的Input,在子組件中聲明一個變量,該變量的值能夠從父組件獲取:html

import { Component,Input,Output,EventEmitter } from '@angular/core';
...
// 父組件傳遞進來的參數
@Input('list') private list:any;
...

父組件中,能夠這樣傳值:java

<my-drop-down-cmp [list]='list'></my-drop-down-cmp>

子組件選擇框發生變化後會通知父組件

實現這個用到了ng2的Output,聲明一個EventEmit的對象,用於向父組件發送消息git

// 當改變了選擇時給父組件發送事件
@Output('selectChange') private selectChange = new EventEmitter();
...
// 當點擊了下拉列表中的某一項
public changeSelect(id: any,text: any,i: any) {
  this.text = text;
  this.id = id;
  // 發送事件
  this._selectChange.emit({id:id,text:text,index:i})
}

父組件中,經過以下方式接收事件:github

<my-drop-down-cmp (_selectChange)='onChangeSelect($event)'></my-drop-down-cmp>
...
// 事件處理函數
onChangeSelect(e:any) {
  this.selectId = e.id;
}

 

 

=============================bootstrap

 

main.ts:app

import {bootstrap} from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component'
import {enableProdMode} from '@angular/core';
import {provideForms, disableDeprecatedForms} from '@angular/forms';

enableProdMode();

bootstrap(AppComponent, [disableDeprecatedForms(), provideForms()]);

app.component.ts:ide

import {Component,ViewChild} from '@angular/core';
import {NgModel} from '@angular/forms';
import {MyDropDownComponent} from './dropdown/my-drop-down';

@Component({
  selector: 'my-app',
  directives: [MyDropDownComponent],
  template: `
  <div id='container'>
    <my-drop-down-cmp [list]='list' [selectId]='list[0].id' (_selectChange)='onChangeSelect($event)'></my-drop-down-cmp>
    <p style='background-color:red;' *ngIf='selectId === 1'>香蕉、西瓜</p>
    <p style='background-color:green;' *ngIf='selectId === 2'>猴子、老虎</p>
  </div>
  `,
  styles:[`
      #container {
        padding-top:100px;
        height:600px;
        width:400px;
        margin:0 auto;
      }
      p {
        margin-top:100px;
      }
    `]
})
export class AppComponent {
  list = [
    {id:1,text:'水果'},
    {id:2,text:'動物'}
  ]
  selectId = 1;
  onChangeSelect(e:any) {
    this.selectId = e.id;
  }
}

my-drop-down.html:函數

<div class="drop-down-container" dropdown>
    <button id="chat-dropdown" type="button" class="btn btn-md btn-primary" dropdownToggle [disabled]="disabled">
                {{text}}<span class="caret"></span>
        </button>
    <ul class="dropdown-menu pull-left" role="menu" aria-labelledby="chat-dropdown">
        <li role="menuitem" *ngFor='let l of list; let i = index'>
            <a class="dropdown-item" href='javascript:;' (click)='changeSelect(l.id,l.text,i)'>
                                {{l.text}}
                            </a>
        </li>
    </ul>
</div>

my-drop-down.ts:優化

import { Component,Input,Output,EventEmitter } from '@angular/core';
import { DROPDOWN_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
    moduleId: module.id,
    selector: 'my-drop-down-cmp',
    templateUrl: 'my-drop-down.html',
    styles: [`
        ul.pull-left {
          left:0 !important;
        }
        .drop-down-container {
          display: inline-block !important;
        }`
    ],
    directives: [DROPDOWN_DIRECTIVES],
    exportAs: 'myDropDown'
})

export class MyDropDownComponent {
    // 默認選擇第一個
    @Input('selectId') private selectId: boolean;
    // 父組件傳遞進來的參數
    @Input('list') private list:any;
    // 當改變了選擇時給父組件發送事件
    @Output('_selectChange') private _selectChange = new EventEmitter();
    private text = '';
    private id:any;

    ngOnInit () {
        if (this.selectId) {
            for (let i=0;i<this.list.length;i++) {
                if (this.list[i].id === this.selectId) {
                    this.text = this.list[i].text;
                    this.id = this.list[0].id;
                }
            }
        }
    }

    public getId () {
        return this.id;
    }

    public changeSelect(id: any,text: any,i: any) {
        this.text = text;
        this.id = id;
        this._selectChange.emit({id:id,text:text,index:i})
    }

}

 

轉發自:http://community.angular.cn/A2AO

相關文章
相關標籤/搜索