Angular2在模板中禁用带有属性的input/select



更新到RC6后,我有选择的问题,这取决于这样一个变量禁用:https://plnkr.co/edit/h1KktXxEfhypHEgefDWQ?p=preview

我已经看了一下这个警告消息,在创建控件时禁用选项设置为true,但它不适合我的需要,因为这不能是动态的(我必须调用。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的一个副本,它不会基于true或false条件禁用输入,但是这个问题对我来说不清楚,我还不能评论

我最终通过创建一个自定义指令得到相同的行为:

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"

我认为你不能使用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');
            });
          }
        }

最新更新