angular - 为什么我无法阻止用户编辑 PrimeNG 表单字段值?

标签 angular primeng angular-reactive-forms angular-forms

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

基本上,在我的组件的 HTML 代码中,我有这样的内容:

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

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

[disabled]="disabled"

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

disabled = true;

所以我期望输入字段编辑被禁用,但事实并非如此,事实上我得到了这个:

enter image description here

奇怪的是,在另一个组件中以这种方式执行它正在工作。唯一的区别是,在另一个组件中,字段未绑定(bind)到表单,但字段值使用 [(ngModel)] 进行绑定(bind),如下所示:

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

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

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

最佳答案

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

对于响应式表单,需要禁用表单控件。

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

关于angular - 为什么我无法阻止用户编辑 PrimeNG 表单字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63883048/

相关文章:

css - 如何使用 TabView 在 Tab 之间添加空格?

angular - 如何使用 RXJS 运算符合并多个 valueChanges 可观察动态

angular - 使用 ng-template 插入响应式表单输入(从组件外部)

angular - 如何在 Angular 应用程序中使用路由更改页面标题?

javascript - 如何在 JQuery 中访问 Angular 6 变量

angular - 如何禁用 FormGroup 中的所有 FormControl

angular - PrimeNG Accordion 中的 ng 模板问题

angular - PrimeNG 主题字体覆盖 Angular 应用程序字体

javascript - FormGroup对象的控件和get方法有什么区别?

angular - 在 Ionic 4 中传递 Iframe src 值