更新到RC6后,我遇到了根据这样的变量禁用的选择问题:https://plnkr.co/edit/h1KktXxEfhypHEgefDWQ?p=preview
我已经看过这个警告消息,在创建控件时将disabled选项设置为true但它不符合我的需要,因为这不是动态的(我必须调用.disable()/。使())
以下是一些代码,以防plnkr不起作用:
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
//this select is disabled
<select formControlName="control1" disabled>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
//This select isn't disabled after RC6 update
<select formControlName="control2" [disabled]="true">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</form>
`,
})
export class App {
form:FormGroup;
constructor() {
this.form = new FormGroup({
control1: new FormControl('2');
control2: new FormControl('2');
});
}
}
注意:这可能与angular2 will not disable input based on true or false condition重复,但这个问题我并不清楚,我无法发表评论
答案 0 :(得分:2)
我最终通过创建自定义指令获得相同的行为:
import { Directive, ElementRef, Input, Renderer } from '@angular/core';
@Directive({ selector: '[customDisabled]' })
export class CustomDisabledDirective {
@Input() customDisabled : boolean;
constructor(private el: ElementRef, private renderer: Renderer) {}
ngOnChanges() {
if(this.customDisabled) {
this.renderer.setElementAttribute(this.el.nativeElement, 'disabled', 'true');
} else {
this.renderer.setElementAttribute(this.el.nativeElement, 'disabled', null);
}
}
}
我现在使用[customDisabled]="myVar"
代替[disabled]="myVar"
。
答案 1 :(得分:0)
我认为你不能使用disabled
作为指令。您必须使用事件来动态启用或禁用HTML元素,如下所示:
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
---
---
//I have applied function on change event; you can use click, onload, etc
<select id="id1" formControlName="control2" (change)="scope()">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</form>
`,
})
export class App {
form:FormGroup;
scope()
{
document.getElementById("id1").disabled=true;
}
constructor() {
this.form = new FormGroup({
control1: new FormControl('2');
control2: new FormControl('2');
});
}
}