2016-09-07 34 views
1

更新到RC6後,我有問題,選擇禁用依賴於這樣一個變量:https://plnkr.co/edit/h1KktXxEfhypHEgefDWQ?p=previewAngular2禁止輸入/用模板屬性選擇

我已經看一看被設置爲禁用選項,此警告消息真的在創建控制,但它不符合我的需要,因爲這不能動態(我必須調用.disable()/ .enable())

這是一些代碼,如果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但這個問題不清楚,我也不能評論

回答

1

我終於通過創建自定義指令獲得相同的行爲:

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"

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'); 
      }); 
      } 
     }