I am working on an Angular project using PrimeNG and I am finding the following difficulties trying to disable the editing of a text form into a field.
Basically into the HTML code of my component I have something like this:
<input id="disabled-input"
type="text"
pInputText
[disabled]="disabled"
formControlName="UID" />
As you can see it is using the formControlName attribute to retrieve data from a FormGroup* object defined into the TypeScript code (it works fine). As you can see I also set this in order to avoid the possibility to edit this field value:
[disabled]="disabled"
Then into the TypeScript code of this component I declared this variable:
disabled = true;
So I expected that the input field editing was disabled but it is not, infact I am obtaining this:
The strange thing is that doing in this way in another component it is working. The only difference is that in this other component the fileds are not bound to a form but the field value is bound useing the [(ngModel)], in this way:
<input id="disabled-input"
type="text"
pInputText
[disabled]="disabled"
[(ngModel)]="orderDetail.UID" />
In this second case it works fine and it is impossible for the user edit the field value.
Why in the first case I can't prevent that the user edit the field value? I can I obtain this behavior?
The first case doesn't work because it is a mix of the template driven and reactive forms. From the Angular docs:
Template-driven forms rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They're easy to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.
IMO avoid template forms for the production software. They are not scalable and testable enough.
For Reactive forms one need to disable the form control.
this.formGroup.get('UID').disable();