For some of my components I would like to change input field readonly and required attributes back and forth.
I've managed to get a running code, that changes both of them on demand, but problem is that it works for readonly, but seems not to be working on required: although element attribute changes to required Angular2 still thinks fieldCtrl is valid.
Here is my plunker, where I illustrated this problem: 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;
}
UPDATE: Tried suggested method
[required]="isRequired" [readonly]="isReadOnly"
And it works like a charm for readonly, and for required=true, but I can't turn the required attribute off anymore - it shows empty field is invalid allthough not required anymore.
Updated plunker: https://plnkr.co/edit/6LvMqFzXHaLlV8fHbdOE
UPDATE2: Tried suggested method
[required]="isRequired ? true : null"
It does add/remove required attribute from element by demand, however field controller's valid property shows false for empty field that is not required.
What would be correct way of changing required attribute in Angular2 Typescript?