2016-07-29 2 views
0

私は角度2のプロトタイプコンポーネントを作成しています。私は同じオプションを持つ2つの選択コントロールを持っています。 2番目のselect要素(destination)では、最初のselect要素(origin)で選択されたオプションを無効にするか、削除したいと思います。あなたは、単に[disabled] DOM属性に結合することによって、オプションを無効にすることができます(なお、第1選択したオプションが表示される理由を任意のアイデア?)angular2セカンダリセレクト要素から選択オプションを削除または無効にします

をここではplunkr

//our root app component 
import {Component} from '@angular/core'; 
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from '@angular/common'; 

@Component({ 
    selector: 'my-app', 
    providers: [], 
    template: ` 
    <div> 
    <h2>{{name}}</h2> 
     <select id="trip_origin" [(ngModel)]="origin" 
     class="start" (change)="onChange($event)"> 
     <option disabled selected >Select a shipping origination</option> 
     <option *ngFor="let item of items" [ngValue]="item"> {{item.name}} - {{item.loc}}</option> 
     </select> 
     <div>selected: {{origin | json}}</div> 
     <hr> 
     <select id="trip_destination" name="destination" [(ngModel)]="destination"> 
     <option *ngFor="let item of items" [ngValue]="item">{{item.name}} - {{item.loc}}</option> 
     </select> 
     <div>selected: {{destination | json}}</div> 
    </div> 

    <h2>Destination -- {{destination.loc}}</h2> 
    <h2>Origin -- {{origin.loc}}</h2> 

    `, 
directives: [] 
}) 

export class App { 

public items:object[] = [ 
    {"loc":"HOU","name":"Houston"}, 
    {"loc":"DAL","name":"Dallas"}, 
    {"loc":"SAT","name":"San Antonion"} 
]; 

constructor() { 
    this.origin={}; 
    this.name = 'Test Select Control' 
    this.destination = this.items[1] 
} 
onChange($event){ 
    console.log($event) 
} 
} 

答えて

1

です:

<select id="trip_destination" name="destination" [(ngModel)]="destination"> 
    <option [disabled]="item === origin" *ngFor="let item of items" [ngValue]="item">{{item.name}} - {{item.loc}}</option> 
      ^^^^^^^^^^ 
</select> 

これにより、現在選択されている "Origin"値が "Destination"セレクタで無効になります(plunker参照)


あなたの他のミニ質問については、「なぜ最初の選択肢がではないのですか?が表示されていますか?これはおそらく、"trip_origin"[(ngModel)]="origin"にバインドされているためです。コンポーネントのコンストラクタにthis.origin = {}を設定します。 this.itemsには対応するオブジェクトがないため、Angularはこの値にバインドする方法を知らない。あなたはありがとう

+0

hereを参照)

<option selected disabled [ngValue]="none">Select a shipping origination</option> 

なると予想されるように続いて、それが表示されます

this.origin=this.none={}; 

を行を持っているのctorを変更するには、このオプションを変更することができます!優れた答え.. – daddyschmack

関連する問題