如何在Angular2 Typescript中更改HTML元素只读和必需属性?

对于我的一些组件,我想改变输入字段readonly和所需的属性来回。

我设法获得一个正在运行的代码,它们根据需要更改它们,但是问题是它可以只读,但似乎没有工作在必需:虽然元素属性更改为所需的Angular2仍然认为fieldCtrl是有效的。

这是我的朋友,我在这里说明了这个问题:https://plnkr.co/edit/Yq2RDzUJjLPgReIgSBAO?p=preview

//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',providers: [],template: `
    <div>
    <form #f="ngForm">
      <button type="button" (click)="toggleReadOnly()">Change readonly!</button>
      <button type="button" (click)="togglerequired()">Change required!</button>
      <input id="field" [(ngModel)]="field" ngControl="fieldCtrl" #fieldCtrl="ngForm"/>
      {{fieldCtrl.valid}}
    </form>
    </div>
  `,directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }

  togglerequired(){
    this.isrequired = !this.isrequired;
    var fieldElement = <HTMLInputElement>document.getElementById('field');
    if (this.isrequired){
      fieldElement.required = true;
      this.field = "it's required Now";
    }
    else{
      fieldElement.required = false;
      this.field = "can leave it blank";
    }
  }

  toggleReadOnly(){
    this.isReadOnly = !this.isReadOnly;
    var fieldElement = <HTMLInputElement>document.getElementById('field');
    if (this.isReadOnly){
      fieldElement.readOnly = true;
      this.field = "it's readonly Now";
    }
    else{
      fieldElement.readOnly = false;
      this.field = "feel free to edit";
    }
  }

  private isReadOnly:boolean=false;

  private field:string = "feel free to edit";

  private isrequired:boolean=false;

}

更新:
尝试建议的方法

[required]="isrequired" [readonly]="isReadOnly"

它的工作原理就像一个只读的魅力,对于required = true,但是我不能再关闭所需的属性 – 它显示空字段是无效的,而不再需要了。

更新补品:https://plnkr.co/edit/6LvMqFzXHaLlV8fHbdOE

UPDATE2:
尝试建议的方法

[required]="isrequired ? true : null"

它通过需求从元素添加/删除必需属性,但是字段控制器的有效属性对于不需要的空字段显示为false。

在Angular2 Typescript中更改所需属性的正确方法是什么?

对于要删除的绑定属性,需要将其设置为null。有一个讨论改变它去除假,但它被拒绝,至少现在。
[required]="isrequired ? '' : null"

要么

[required]="isrequired ? 'required' : null"

您的Plunker因为在ngControl周围缺少[]而产生错误

另见这个Plunker一个工作的例子

另见Deilan的评论如下。

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...