I am facing an issue with changing input field attributes back and forth in some of my components. I have a code that successfully changes the readonly attribute as needed. However, when trying to change the required attribute, Angular2 still considers the fieldCtrl valid even after making the change.
You can see the problem illustrated in this Plunker: 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;
}
I have tried suggested method
[required]="isRequired" [readonly]="isReadOnly"
This works well for readonly and for required=true. However, I am unable to turn off the required attribute anymore, as it shows the empty field is invalid even though it's not required.
Updated Plunker here: https://plnkr.co/edit/6LvMqFzXHaLlV8fHbdOE
I also attempted the following method
[required]="isRequired ? true : null"
Although this method successfully adds/removes the required attribute as needed, the field controller's valid property still shows false for an empty field that is not required.
Can someone advise on the correct way to change the required attribute in Angular2 Typescript?