2016-09-07 5 views
1

における属性で選択/入力を無効にしますコントロールの作成には当てはまりますが、これは動的ではないため、私の必要に合わないためです(私は.disable()/ .enable()を呼び出さなければなりません)Angular2はRC6にアップデートした後、私はこのような変数に応じて無効になっている選択に問題があるテンプレート

ここでは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'); 
      }); 
      } 
     } 
関連する問題