2017-12-04 15 views
0

私はフォーム内に選択肢のグループを作成しようとしています。これは、ユーザーが何を選択しているかに応じて変化します(ユーザーは選択項目を順番に選択する必要があります)。Reactive select in Angular2

問題は、主に私のonChange()関数にあります。なぜなら、ユーザがキャンパスを選択したときに変更を正しく保存していないように見えるからです。ユーザーがCampus1を選択した場合、「建物」選択はオプションとして「2」のみを表示し、ユーザーがCampus2を選択した場合、「建物」選択はオプションとして「4」のみを表示する必要があります。

また、私はちょうど今でいじってるので、私のアプローチは、非常に正しいかどうかはわからないけど、この作品とき、私はアプリは次の操作を実行したい:

  1. は(場所のデータを取得します。キャンパス、ビルディング、フロア、ゾーン)を私の職場に持っているAPIから取得するとJSONが与えられます。
  2. 私がやっていること、つまり、ユーザーが選択した内容に応じて、特定のオプションを指定します。
  3. 次に、ユーザーはこのフォーム(基本的にはフィルタリング)を別のAPIに送信してロッカー情報を取得できます。

これに関するヘルプはありますか?特に最初の部分ですが、私が第二部でやりたいことを達成するために正しい道にいるかどうか教えてもらえれば素晴らしいでしょう。私は反応形式に関するAngularの文書を読んだことがありますが、それを正しく行う方法はわかりません。前もって感謝します。 ngModelは、あなたがそれ(のonChange)を変更するときdetection.Itの火災を変更するが、値 'cumpus' 更新されていないと

import {Component} from 'angular2/core'; 
    class Locker { 
     constructor(public Campus: string, public Building: string, public Floor: string, public Zone: string, public Type: string) { } 
    } 

    @Component({ 
     selector: 'my-app', 
     template: ` 
     <div class="column small-12 large-2"> 
     <label class="sbw_light">Campus</label><br /> 
     <select name="campus" [(ngModel)]="campus" (change)="onChange()"> 
      <option *ngFor="#each of lockers" [value]="each.Campus"> 
       {{each.Campus}} 
      </option> 
     </select> 
     <br> 
      <label class="sbw_light">Building</label><br /> 
     <select name="building" [(ngModel)]="building"> 
      <option *ngFor="#each of buildings"> 
      <div *ngIf="campus == 'Campus1'"> 
       {{each}} 
       </div> 
      </option> 
     </select> 
     </div> 
     ` 
    }) 
    export class AppComponent { 

     campus: String = ""; 
     building: String = ""; 
     floor: String = ""; 
     zone: String = ""; 
     type: String = ""; 

     lockers: Locker[] = [new Locker("Campus1", "2", "2", "B", "Simple"), 
          new Locker("Campus2", "1", "1", "C", "Simple"), 
          new Locker("Campus2", "1", "0", "A", "Simple")]; 

     buildings = []; 
     floors: = []; 
     zones: = []; 
     types: = []; 

     onChange(){ 
     console.log(campus); 
     if (campus == 'Campus1'){ 
      this.buildings.length = 0; 
      this.buildings.push("2"); 
     } 
     else{ 
      this.buildings.length = 0; 
      this.buildings.push("4"); 
     } 
     } 

    } 

答えて

1

問題:

は、ここに私のTSファイルです。だからあなたのようなものを使用する必要があります

valueChanged(event: any) { 
    const campus = event.target.value; 
    console.log(campus); 
    if (campus == 'Campus1'){ 
     this.buildings.length = 0; 
     this.buildings.push("2"); 
    } 
    else{ 
     this.buildings.length = 0; 
     this.buildings.push("4"); 
    } 
+0

おかげ

(onChange)="valueChanged($event)" 

そして、あなたのコンポーネント内に、それが完全に働きました。ちょうどconsole.logが必要ではないことを指摘したいが、誰かがこの答えを見る場合に備えて、デバッグには良いかもしれない。 –