[英]How to make a formControl readonly
如何以只读方式制作角度的formControl
我知道我可以在 html 中做到这一点
<input type="text" formControlName="xyz" readonly />
如何从 JS 代码而不是 html 即以模型驱动的方式进行
如果您使用的是响应式表单,您可以像下面的示例代码(电子邮件字段)一样动态分配它
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],
});
如果您想获取包括禁用控件在内的所有值,您应该使用:
this.registerForm.getRawValue();
查看源代码上的方法注释
/**
* 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;
享受编码!
在我的猜测中,没有在反应形式(Angular 2+)中使用READONLY 。
我们使用READONLY属性来防止用户输入/选择表单控件,但我们从输入中获取值。
我们使用DISABLED属性来防止用户键入/选择表单控件,并且我们不会从输入中获取值。
我们不需要READONLY属性来防止用户输入/选择。 因为DISABLED属性足以防止用户输入/选择,而且您还可以从禁用的输入/选择/复选框/单选字段中获取值。
您可以以模型驱动的方式向字段添加禁用属性
创建 FormGroup 时
this.formGroupName = this.fb.group({
xyz: [{ value: '', disabled: true }, Validators.required]
});
在运行时
this.formGroupName.get('xyz').disable({ onlySelf: true });
从 FormGroup 获取值(已编辑)
仅从未禁用的字段中获取值
this.formGroupName.value;
获取 FormGroup 中所有字段的值
this.formGroupName.getRawValue();
所以在这里你不需要 READONLY 属性。 希望它有帮助。
我们可以使用任何 html 属性并使用[]
以角度绑定它。
因此,您可以在该控件中为属性readonly
使用属性绑定
例如
<input type="text" formControlName="xyz" [readonly]="anyBooleanPropertyFromComponent" />
对于reactive-forms
,如果你想让字段只读,一种方法是使用普通的旧javascript:
(document.getElementById('abc') as HTMLInputElement).setAttribute('readonly','true');
除此之外,您还可以将代码转换为更多的打字稿和角度方式。 使用@ViewChild
访问元素,然后将readonly
属性设置为 true:
HTML
<input [formControl]='data' id='abc' #element [readonly]="data.disabled"/>
TS
@ViewChild('element',{static:true, read: ElementRef}) element : ElementRef ;
(this.element.nativeElement as HTMLInputElement).readOnly = true;
但是,您需要在修改 readonly 属性之前检查 formControl 的状态。
将表单控件设置为disabled
control = new FormControl({ value: '', disabled: true })
以编程方式enable
/ disable
表单控件
<button (click)="enable()">Enable</button>
<button (click)="disable()">Disable</button>
disable() {
this.control.disable()
}
enable() {
this.control.enable()
}
如果使用表单构建器,使用反应式表单:
this.customerForm = this.formBuilder.group({
customerName: [{value: null, disabled: true}, Validators.required],
})
一个简单的解决方案是将表单控件设置为未禁用:
this._formBuilder.group({
some: new FormControl(
{
value: parseInt(this.myobject.subObject.stringMember),
disabled: false
},
Validators.required
),
同时,将<input>
和/或<textarea>
为只读:
<label> <span class="label">SomeLabel</span> <textarea maxlength="500" formControlName="some" readonly> </textarea> </label>
<input type="text" formControlName="name" />
这至少适用于 input 和 textarea 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.