【Angular】——无限级下拉列表框

来源:互联网 发布:mysql select unique 编辑:程序博客网 时间:2024/05/17 09:36

  前言


  前段时间换了新框架,将前后端分离,对Angular2有点感兴趣,所以参与一起封装组件。在小5的帮助下,学会了

好多东西,这里总结下封装的无限级下拉列表框。


 dropdownlist.ts

 

import { Component,OnInit,Output,EventEmitter,Input } from '@angular/core';import { URLSearchParams }                            from '@angular/http';import {DataService}                                  from "./dataservice";@Component({    selector:'dropdownlist',    templateUrl:'./dropdownlist.component.html',      styleUrls:['./dropdownlist.component.css'],    })export class DropDownListComponent{      @Input() urls:String[][] = new Array();//保存传递过来的url    datas:String[][] = new Array(); //保存查询结果    @Input() titles:String[][] = new Array();//保存提示语句    condition:string = "";//查询条件    index:number = 0;    constructor(public dataService : DataService ){}       ngOnInit(){                this.getData(this.condition,this.index);               }    getData(condition : string,index : number ):void{                      var condition = (condition == "" ? "" : condition);                       if(index < this.urls.length){                     let url = this.urls[index].toString() + condition;              this.dataService.getData(url).then( res=>            {                             this.datas[index] = res;                                           });                }           }    dataChange(condition:string,i:number){                       this.getData(condition,i+1);    }}

  dropdownlist.component.html

 

<div>  <select name="data" class="combobox form-control"  *ngFor="let url of urls,let i = index" (change)="dataChange($event.target.value,i)">    <option value="-1">--{{titles[i]}}--</option>    <option *ngFor="let item of datas[i]" value="{{item.id}}" >{{item.name}}</option>  </select></div>


  组件应用


  上边就是我封装无限级下拉列表框所用的关键代码,将上述的组件发布之后,将组件down下来并引用,下拉列表

框的组件就可以投入使用了。代码部分:

  app.module.ts代码:

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { HttpModule } from '@angular/http';import { DropDownListModule } from 'ng-itoo-dropdownlist';import { AppComponent } from './app.component';@NgModule({  declarations: [    AppComponent  ],  imports: [    BrowserModule,    FormsModule,    HttpModule,       DropDownListModule   ],  providers: [],  bootstrap: [AppComponent]})export class AppModule { }

  app.component.html代码:

<dropdownlist [titles]='titles' [urls]='urls' ></dropdownlist >

  app.component.ts代码:

import { Component } from '@angular/core';@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  titles = ['请选择省份','请选择市','请选择区县'];  urls=['http://localhost:8081/rest/item/countries','http://localhost:8081/rest/item/provinces/','http://localhost:8081/rest/item/cities/'];  // titles = ['请选择省份'];  // urls=['http://localhost:8081/rest/item/countries'];}

  页面效果:


原创粉丝点击