对于我的一些组件,我想改变输入字段readonly和所需的属性来回。
原文链接:https://www.f2er.com/angularjs/144160.html我设法获得一个正在运行的代码,它们根据需要更改它们,但是问题是它可以只读,但似乎没有工作在必需:虽然元素属性更改为所需的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"