选择Angular2中的事件

kak*_*aja 9 html javascript dom angular

拜托,你能帮帮我吗?它应该很容易,但我找不到解决方案.有一个有两个选择的表单.#select1更改时,#select2需要根据#select1的值显示数据.例如,获取每个州的城市.的种类 :

//html

<select (change)="select2.getCities($event)" ng-control="userState">
    <option *ng-for="#state of states" [value]="state">{{state}}</option>
</select>

<select #select2 ng-control="userCity">
    <option *ng-for="#city of cities" [value]="city">{{city}}</option>
</select>

//the Component
@Component({ selector: 'user-management', appInjector: [FormBuilder] });
@View({ templateUrl: 'user-management.html', directives: [NgFor] });
export class userManagement {
    constructor(fb: FormBuilder){
        this.userForm = fb.group({
            userState: [],
            userCity: []
        });
        this.states = ['New York', 'Pennsylvania'];
        this.cities = {'New York': ['Albany', 'Buffalo'], 'Pennsylvania':['Pittsburgh', 'Philadelphia']};
    }
    getCities($event){
        return this.cities[$event.target.value];
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,这不起作用.请问,你知道应该怎么做吗?它在alpha28中.

kak*_*aja 6

大!我发现了如何使它工作!:)唯一缺少的是传递给事件的表单模型.它应该是这样的:

<form [ng-form-model]="userForm">
<select (change)="select2.getCities($event, userForm)" ng-control="userState">
    <option *ng-for="#state of states" [value]="state">{{state}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)


San*_*dhe 5

回答Angular 2最新的模板语法和Typescript组件

   //The Component Type script
import {Component} from 'angular2/core';
import {NgForm}    from 'angular2/common'; 

@Component({ selector: 'states-cities', 
             template: `
                    <form (ngSubmit)="onSubmit()" #heroForm="ngForm"> 
                       <select  ngControl="state" #state="ngForm" (change)="getCities(state)">
                            <option *ngFor="#state of states" [value]="state" >{{state}}</option>
                        </select>

                        <select  ngControl="userCity" #select2="ngForm">
                            <option *ngFor="#city of cities" [value]="city">{{city}}</option>
                        </select>
                      </form>
                     `


           })
export class stateCitiesComponent {

     states= ['New York', 'Pennsylvania'];
     cities = [];
     citiesData={'New York': ['Albany', 'Buffalo'], 'Pennsylvania':['Pittsburgh', 'Philadelphia']};

    getCities(state){
         this.cities=this.citiesData[state.value];
    }
}
Run Code Online (Sandbox Code Playgroud)