如何使 formControl 只读 [英] How to make a formControl readonly

查看:34
本文介绍了如何使 formControl 只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使 angular 的 formControl 只读

我知道我可以在 html 中做到这一点

如何从 JS 代码而不是 html 中做到这一点,即以模型驱动的方式

解决方案

如果您使用的是响应式表单,您可以像这样动态分配它下面的示例代码(电子邮件字段)

 this.registerForm = this.formBuilder.group({first_name: ['', Validators.required],last_name: ['', Validators.required],电子邮件:新 FormControl({value: null, disabled: true}, Validators.required),密码:['', Validators.compose([Validators.required, Validators.email])],确认密码:['',Validators.required],});

如果您想获得包括禁用控件在内的所有值,您应该使用:

 this.registerForm.getRawValue();

<块引用>

查看源代码的方法注释

/*** `FormGroup` 的聚合值,包括任何禁用的控件.** 如果您想包括所有值而不考虑禁用状态,请使用此方法.* 否则,`value` 属性是获取组值的最佳方式.*/getRawValue(): 任何;

享受编码!

How to make a formControl in angular readonly

I know i can do it in html like

<input type="text" formControlName="xyz" readonly />

how to do it from JS Code and not html i.e in a model driven way

解决方案

If you are using Reactive Forms you can assign it dynamically like in the example code below (email field)

    this.registerForm = this.formBuilder.group({
          first_name: ['', Validators.required],
          last_name: ['', Validators.required],
          email: new FormControl({value: null, disabled: true}, Validators.required),
          password: ['', Validators.compose([Validators.required, Validators.email])],
          confirm_password: ['', Validators.required],
    });

If you want to get all the values including disabled controls you should use:

    this.registerForm.getRawValue();

View method comment on source code

    /**
       * The aggregate value of the `FormGroup`, including any disabled controls.
       *
       * If you'd like to include all values regardless of disabled status, use this method.
       * Otherwise, the `value` property is the best way to get the value of the group.
       */
      getRawValue(): any;

Enjoy coding!

这篇关于如何使 formControl 只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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