在 angular 2 表单中禁用默认下拉值的提交按钮

Disable the submit button for the default Dropdown value in an angular 2 Form

我有一个 select 国家/地区下拉菜单,它有一个默认值 "Select"。页面底部有一个提交按钮,只有当下拉菜单包含一些国家/地区值时才应启用该按钮。对于默认值,该按钮应被禁用,因为它是必填字段。

我在 .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 禁用整个下拉菜单。谁能告诉我哪里出错了。

您需要让 parent 组件知道某个国家/地区何时被 selected。

从您的country-component

定义一个输出参数

添加导入

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

并添加你的输出参数

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

您需要在 selected 国家/地区时发出该输出。将以下功能添加到您的 country-component

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

您还需要对 select 进行更改以调用新的 onChange 函数

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

现在您的 country-component 已准备好让 parent 知道某个国家/地区何时被 select 编辑。

在 parent 组件中定义输出参数,例如:

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

并在您的 parent 组件中定义一个函数

submitEnabled : bool = false;

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

并将您的按钮绑定到您的 submitEnabled 变量。

<button [disabled]="!submitEnabled">Submit</button>