为什么我不能阻止用户编辑 PrimeNG 表单字段值?

Why I can't prevent that the user edit a PrimeNG form field value?

我正在使用 PrimeNG 开发一个 Angular 项目,我发现在尝试禁用将文本表单编辑到字段中时遇到以下困难。

基本上进入我的组件的 HTML 代码我有这样的东西:

<input id="disabled-input"
       type="text"
       pInputText
       [disabled]="disabled"
       formControlName="UID" />

如您所见,它使用 formControlName 属性从 TypeScript 代码中定义的 FormGroup* 对象中检索数据(它工作正常)。如您所见,我还设置了此项以避免编辑此字段值的可能性:

[disabled]="disabled"

然后在这个组件的TypeScript代码中我声明了这个变量:

disabled = true;

所以我预计输入字段编辑被禁用但它没有,事实上我得到这个:

奇怪的是,以这种方式在另一个组件中工作。唯一的区别是,在这个其他组件中,字段未绑定到表单,但字段值使用 [(ngModel)] 绑定,以这种方式:

    <input id="disabled-input"
           type="text"
           pInputText
           [disabled]="disabled"
           [(ngModel)]="orderDetail.UID" />

在第二种情况下,它工作正常,用户不可能编辑字段值。

为什么在第一种情况下我不能阻止用户编辑字段值?我可以获得这种行为吗?

第一种情况不起作用,因为它混合了模板驱动和反应形式。来自 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 避免生产软件的模板表格。它们的可扩展性和可测试性不够。

对于 Reactive 表单,需要禁用表单控件。

this.formGroup.get('UID').disable();

虽然它可能不是你正在寻找的,而不是

[已禁用]="已禁用"

我用过

readonly="只读"

实现这一点。该字段未被禁用,但无法更改,这是我的目标。

      <input readonly="readonly" pInputText class="p-inputtext-sm" formControlName="featureName" />