我想以编程方式禁用SELECT标记中的ar选项,并以此方式进行了尝试,但是它不起作用。 我需要一些指导:)
TS文件:
...
formGroup = new FormGroup({
sel: new FormControl()
});
ngOnInit() {
this.formGroup.get("sel").get("a").disable();
}
HTML文件:
<select formControlName="sel">
<option value="a">a</option>
<option value="b">b</option>
</select>
答案 0 :(得分:2)
您可以将[disabled]
属性用于动态检查。
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
<select formControlName="cityName">
<option value="">Choose your city</option>
<option *ngFor="let city of cityList" [ngValue]="city" [disabled]="isSelected(city)">{{city}}</option>
</select>
<button type="submit" class="btn btn-danger btn-lg btn-block">Submit</button>
</form>
<br>
<hr>
<br>
<div *ngIf="selectedCityList.length > 0" class="city-list"><strong>Selected City : </strong><br><div *ngFor="let removeCity of selectedCityList"><span class="remove-city" title="Click to Remove" (click)="removeSelectedCity(removeCity)">Remove</span> {{removeCity}}</div></div>
对于.ts
文件,我创建了3个功能-一个将添加到SelectedCity,第二个将检查所选城市是否在SelectedCity中,第三个将从SelectedCity中删除。
registrationForm = this.formBuilder.group({
cityName: ["", [Validators.required]]
});
onSubmit() {
if(!this.selectedCityList.includes(this.registrationForm.get("cityName").value)){
console.log(this.registrationForm.get("cityName").value);
this.selectedCityList.push(this.registrationForm.get("cityName").value);
}
}
isSelected(city){
return this.selectedCityList.includes(city);
}
removeSelectedCity(city){
if(this.selectedCityList.includes(city)){
this.selectedCityList.splice(this.selectedCityList.indexOf(city), 1);
}
}
答案 1 :(得分:1)
如果要禁用侧面的选项,则可以在传统的模型驱动方法中使用[attr.disabled]
。
<select >
<option [attr.disabled] = "true" value="a">a</option>
<option value="b">b</option>
</select>
否则,您可以传递[attr.disabled]
一个谓词,该谓词的评估结果为true或false。
请找到Stackblitz here
但是,如果您想使用反应式表单方法。这可以在表单级别而不是FormGroup级别完成。订阅反应形式时,您可以在选择更改事件中提出解决方案。
在您的反应形式模板中:
<select (change)="changeCity($event)"formControlName="cityName">
<option value="">Choose your city</option>
<option *ngFor="let city of City" [ngValue]="city">{{city}}</option>
</select>
在您的打字稿控制器中:
export class AppComponent {
City: any = [1, 2, 3, 4];
constructor(public fb: FormBuilder) {
this.registrationForm.get("cityName").valueChanges.subscribe(val => {
if (val == 1) {
this.registrationForm.get("cityName").reset();
return;
} else {
this.registrationForm.get("cityName").enable();
}
});
}
}
如果用户选择1
选项,它将重置其值并返回。请找到StackBlitz here。