Angularjs2-下拉列表实现(父子组件通信)

基于http://valor-software.com/ng2-bootstrap/#/dropdowns 做的一个下拉列表控件,优化了如下功能,项目地址

  • 列表内容由父组件传递
  • 子组件选择框发生变化后会通知父组件

demo

demo-new.gif

列表内容由父组件传递

这个主要利用到了ng2的Input,在子组件中声明一个变量,该变量的值可以从父组件获取:

import { Component,Input,Output,EventEmitter } from '@angular/core';
...
// 父组件传递进来的参数
@Input('list') private list:any;
...

父组件中,可以这样传值:

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

子组件选择框发生变化后会通知父组件

实现这个用到了ng2的Output,声明一个EventEmit的对象,用于向父组件发送消息

// 当改变了选择时给父组件发送事件
@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})
}

父组件中,通过如下方式接收事件:

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

 

 

=============================

 

main.ts:

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:

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

 

posted on 2016-12-01 17:04  cjxhd  阅读(1967)  评论(0编辑  收藏  举报

导航