2016-10-28 7 views
0

"Select"というデフォルト値を持つselect countryドロップダウンがあります。ドロップダウンにいくつかの国の値がある場合にのみ有効になるように、ページの下部に送信ボタンがあります。デフォルト値の場合、ボタンは必須フィールドとして無効にする必要があります。角度2のデフォルトのドロップダウン値の送信ボタンを無効にするフォーム

私の.tsファイルのドロップダウンのコンポーネントを作成しました。

@component({ 

selector:'country-component', 
template:'<form> 
<select> 
<option [disabled]="butDisabled">Select</option> 
<option [value]="" *ngFor="let country of countryList">{{country.label}}</option> 
</select> 
</form>' 

}) 

export class countryComponent implements onInit{ 
butDisabled: boolean = true; 
} 
私のHTML-で

<country-component (ngModelOptions)="{standalone:true}" name=""></country-component> 

<button>Submit</button> 

これはwork.Itは全体のドロップダウンが無効になりません。私が間違っている場所を誰にでも教えてもらえますか?

+0

ボタンの定義はどこですか?私は2つの選択肢を見る。 –

+0

@John Baird更新されたコードを参照してください。 –

答えて

1

国が選択されたときに親コンポーネントに通知する必要があります。

はあなたcountry-component

追加インポート

import { Output, EventEmitter } from '@angular/core'; 

からの出力パラメータを定義し、出力パラメータは、あなたが国を選択したときにその出力を放出する必要が

export class countryComponent implements onInit{ 
    @output countrySelected = new EventEmitter(); // <-- define output parameter 
} 

を追加します。 country-component

onChange(selectedCountry) { 
    this.countrySelected.emit(selectedCountry); // <-- emit when a country selected 
} 

はまた、あなたがあなたのcountry-componentが国である場合は、親に知らせする準備ができていることを今

<select (change)="onChange($event.target.value)"> 
    <option>Select</option> 
    <option [value]="" *ngFor="let country of countryList">{{country.label}</option> 
</select> 

新しいonChange関数を呼び出すためにあなたの選択に変更を加える必要があり、あなたに次の関数を追加します。選択された。

のようなあなたの親コンポーネントで出力パラメータを定義します。

<country-component (ngModelOptions)="{standalone:true}" name="" (countrySelected)="enableSubmit($event)"></country-component> 

とあなたの親コンポーネント

submitEnabled : bool = false; 

enableSubmit(event: any){ 
    this.submitEnabled = true; 
} 

で関数を定義し、あなたのsubmitEnabled変数にあなたのボタンをバインドします。

<button [disabled]="!submitEnabled">Submit</button> 
関連する問題