2016-10-28 67 views
0

我有一個選擇國家下拉列表,其中有一個名爲「選擇」的默認值。頁面底部有一個提交按鈕,只有在下拉菜單中有一些國家/地區值時才能啓用該按鈕。對於默認值,該按鈕應該被禁用,因爲它是一個必填字段。以角度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

按鈕定義在哪裏?我看到兩個選項。 –

+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 
} 

而且你需要在你選擇的變化打電話給你的新onChange功能

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

現在,你的country-component是準備讓父母知道當一個國家選擇。

在喜歡你的父組件定義輸出參數:

<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>