Angular: Form fields read-only mode

karthikaruna picture karthikaruna · Nov 15, 2017 · Viewed 12.8k times · Source

I have some forms that should be editable only by some users. Other users should only be able to view it.

Currently, for each form control in a form, I'm checking condition and displaying either a form control or a text. Something like,

<div>
    <input type="text" *ngIf="editable">
    <p *ngIf="!editable">{{value}}</p>
</div>

This doesn't seem to be an elegant way. Please suggest a cleaner way to achieve this, like doing something at the top level.

Answer

tasos picture tasos · Nov 15, 2017

Since you are using Angular, it is better to use FormControls and FormGroups. Take a look at this guide. Using the FormControl API you can enable and disable the input programmatically.

An other way is to use property binding and do something like this:

<div>
   <input type="text" [readonly]="!editable">
</div>