2

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.

karthikaruna
  • 3,042
  • 7
  • 26
  • 37
  • 1
    Why can't you make 2 different views (readonly and editable) rather than toggling each control separately? – Zabavsky Nov 15 '17 at 14:37

2 Answers2

4

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>
tasos
  • 369
  • 1
  • 9
  • 1
    No. I don't wanna use `readonly` or `disabled` attribute. I want to show a static element instead of a form control like `select` or `input`, but without toggling each control individually. – karthikaruna Nov 15 '17 at 15:35
  • I am not sure that I understand what you mean. If you style your input to look like a "static" element? – tasos Nov 15 '17 at 15:46
  • Angular doesn't encourage binding to `disabled` elements. I can't use `readonly` as my forms have `select` element and `readonly` doesn't have any effect on them. Moreover, I primarily don't want to toggle each element individually. – karthikaruna Nov 15 '17 at 16:45
-1

I think you should take a look to the ng-disabled directive. This should do the trick here!

Marvin
  • 1,650
  • 4
  • 19
  • 41
  • Your link is for Angular 1.x and the questions source is Angular 2+. – tasos Nov 15 '17 at 14:57
  • My bad srry. The answer was given here : https://stackoverflow.com/questions/37159827/is-there-any-alternative-for-ng-disabled-in-angular2 – Marvin Nov 16 '17 at 09:14