使用 Material Design 和 ReactiveForms 的 Angular2 级联下拉菜单

标签 angular material-design lodash cascadingdropdown onselect

我正在使用 Material Design 和 ReactiveForms 来处理级联下拉菜单。该代码有一个州的下拉列表,一旦选择,将过滤城市的下拉列表。

我找到了这个例子http://www.talkingdotnet.com/cascading-dropdown-select-list-using-angular-js-2/但它没有使用reactiveForms。

当前屏幕加载没有错误。州的下拉列表中有一个州列表。选择状态时会发生这种情况... ./MainComponent 类 MainComponent - 内联模板中的错误:11:16 导致:无法读取未定义的属性“值”

这是状态界面

export interface IState {
    state: string;
}

这是城市的界面

    export interface ICity {
    state: string;
    city: string;
}

这是城市的服务

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/distinct';
import 'rxjs/add/operator/catch';
import { ICity } from './city.interface'

@Injectable()
export class CityService {
  private _urlCity = '../../api/city.json';

  constructor(private _http: Http) { }

  getCity(stateName:string): Observable<ICity[]> {
    return this._http.get(this._urlCity)
      .map((response: Response) => <ICity[]>response.json())
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error('I found something bad');
    console.error(error);
    return Observable.throw(error.json().error || 'Server error ...');
  }


}

这是主要组件的 HTML`

<div class="card-container">
  <md-card>
    <md-card-title>
      <h3>Testing Cascade Material Design</h3>
    </md-card-title>
    <md-card-content>
      <div *ngIf='allStates'>
        <form novalidate [formGroup]="myForm">
          <div class="flex-container" fxLayout="row" fxLayoutAlign="left left">
            <div class="flex-container" fxLayout="row" fxLayoutGap="20px" fxLayoutAlign="space-around space-around" fxFlex="97%">
              <div class="flex-oneStudent" fxFlex="10%">
                <md-select placeholder="State" formControlName="state" required="true" (change)="onSelect($event.target.value)">
                  <md-option *ngFor="let oneState of allStates" [value]="oneState.state">
                    {{ oneState.state }}
                  </md-option>
                </md-select>
              </div>
              <div class="flex-oneStudent" fxFlex="20%">
                <md-select placeholder="City" formControlName="city" required="true">
                  <md-option *ngFor="let oneCity of cityByState" [value]="oneCity.city">
                    {{ oneCity.city }}
                  </md-option>
                </md-select>
              </div>
              <div fxFlex="67%"> </div>
            </div>
          </div>
        </form>
      </div>
    </md-card-content>
  </md-card>

这是主要组件

import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { StateService } from '../State/state.service';
import { CityService } from '../City/city.service';
import { IState } from '../State/state.interface';
import { ICity } from '../City/city.interface';

import * as _ from 'lodash';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
  myForm: FormGroup;
  allStates: IState[];
  cityByState: ICity[];

  constructor(public fb: FormBuilder,
    private _StateService: StateService,
    private _CityService: CityService
  ) { }

  ngOnInit() {
    this.myForm = this.fb.group({
      state: '',
      city: ''
    });

    this._StateService.getState()
      .subscribe(
      stateData => this.allStates = _.uniqBy(stateData, 'state')
      );
  }

  onSelect(stateName) {
    console.log ('User selected ' + stateName);
    this._CityService.getCity(stateName)
      .subscribe(
      cityData => this.cityByState = _.filter(cityData, function(o) { return o.state == stateName})
      );

  }

}

这里是完整代码的 github。 https://github.com/ATXGearHead12/cascade

最佳答案

您需要看一下素材源代码https://github.com/angular/material2/blob/master/src/lib/select/select.ts#L247

@Output() change: EventEmitter<MdSelectChange> = new EventEmitter<MdSelectChange>();

如您所见,已发出带有 MdSelectChange 负载的事件

export class MdSelectChange {
  constructor(public source: MdSelect, public value: any) { }
}

所以替换

(change)="onSelect($event.target.value)"

(change)="onSelect($event.value)"

* 自 Angular 6 起,(change) 被贬值,转而支持 (selectionChange)
see material 2 Breaking Changes > deprecations

(selectionChange)="onSelect($event.value)"

关于使用 Material Design 和 ReactiveForms 的 Angular2 级联下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632545/

相关文章:

angular - 如何将 html 绑定(bind)到 Angular 2.0

wpf - Dragablz tabablzcontrol

material-design - 如何在移动 View 上隐藏 Material-Ui Mini 变体抽屉

javascript - LoDash 挑战,我有一组需要过滤的对象,用于一组值

javascript - 如何在 Javascript/Lodash/ES6 中搜索父对象和子对象?

angular - Angular 如何使用 *ngFor 过滤未知数量的元素?

angular - Chart.js v2 图表不显示在 Angular 2 内(但 Chart.js v1 完美运行)

android - 错误 : IllegalArgumentException: The style on this component requires your app theme to be Theme. Material 组件

javascript - 什么是 clojure.core 相当于 lodash _.pluck

javascript - 如何以 Angular 将数据导入html