如何以角度禁用模板驱动表单中的所有字段 [英] How to disable all the fields in a template driven form in angular

查看:29
本文介绍了如何以角度禁用模板驱动表单中的所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angular 5 中创建了一个模板驱动的表单

I created a template driven form in angular 5

我想首先禁用整个表单,并且还希望在单击某个按钮后启用该表单,因此我在表单标签中添加了一个 disabled 属性并将其值设置为 false ,如下所示,(这没有虽然不起作用):

I want to disable the whole form at first, and also want the form to be enabled once some button is clicked, Hence I added a disabled property in the form tag and made its value as false as shown below , (this didn't work though):

<form #formName = "ngForm" [disabled]="true">
</form>

由于上述禁用属性不起作用,我将禁用属性更改为

As the above disabled property didn't work, I changed the disabled property as

[attr.disabled] = true

这也不起作用

现在我有了表单元素的引用,它是 #formName,我在 TS 文件中使用它并尝试更改引用对象内的禁用属性值

Now as I have the form element's reference which is #formName, I used it in the TS file and tried to change the disabled property value inside the reference object

这是我所做的:

@ViewChild('formName') formName;


this.formName.disabled = true; 

这也不起作用,我收到一条错误消息说禁用无法更改,因为它只是一个 getter

which also didn't work and I got an error message saying disabled cannot be changed as it is only a getter

我应该如何在模板驱动的表单上默认禁用整个表单?

How should I disable the whole form by default in angular on template driven forms ?

提前致谢:)

推荐答案

如评论中所述,您可以将表单包装在 fieldset 标签内,并实现如下:

As mentioned in the comment you can wrap the form inside a fieldset tag and achieve this as below:

<form>
    <fieldset [disabled]="fieldsetDisabled">
        <!-- YOUR FIELDS HERE -->
    </fieldset>
</form>

并且您可以通过切换局部变量和在 disabled/enabled 状态之间更改控制器中的状态:

And you can change handle the state in your controller by toggling a local variable and between the disabled/enabled states as:

this.fieldsetDisabled = true;  // Disables the fieldset
this.fieldsetDisabled = false; // Enables the fieldset

这篇关于如何以角度禁用模板驱动表单中的所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆