Ank*_*nka 20 angular angular-reactive-forms
如何在有角度的readonly中进行formControl
我知道我可以用html这样做
<input type="text" formControlName="xyz" readonly />
Run Code Online (Sandbox Code Playgroud)
如何从JS代码而不是html,即以模型驱动的方式
Erv*_*jku 30
如果您使用的是Reactive Forms,则可以像下面的示例代码一样动态分配它(电子邮件字段)
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],
});
Run Code Online (Sandbox Code Playgroud)
如果要获取包括禁用控件在内的所有值,则应使用:
this.registerForm.getRawValue();
Run Code Online (Sandbox Code Playgroud)
查看方法对源代码的评论
/**
* 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;
Run Code Online (Sandbox Code Playgroud)
享受编码!
sil*_*R.D 15
在我的猜测中,没有在反应形式(Angular 2+)中使用READONLY。
我们使用READONLY属性来防止用户键入/选择表单控件,但是我们从输入中获取值。
我们使用DISABLED属性来防止用户键入/选择表单控件,而我们从输入中没有获得价值。
我们不需要READONLY属性来防止用户键入/选择。因为DISABLED属性足以阻止用户键入/选择,而且您还可以从禁用的输入/选择/复选框/无线电字段中获取值。
您可以通过模型驱动的方式向字段添加禁用的属性
在创建FormGroup时
this.formGroupName = this.fb.group({
xyz: [{ value: '', disabled: true }, Validators.required]
});
Run Code Online (Sandbox Code Playgroud)
在运行时
this.formGroupName.get('xyz').disable({ onlySelf: true });
Run Code Online (Sandbox Code Playgroud)
从FormGroup获取值(已编辑)
仅从非禁用字段获取值
this.formGroupName.value;
Run Code Online (Sandbox Code Playgroud)
获取FormGroup中所有字段的值
this.formGroupName.getRawValue();
Run Code Online (Sandbox Code Playgroud)
因此,这里不需要READONLY属性。希望能帮助到你。
我们可以使用任何html属性并使用角度绑定它[].
因此,您可以readonly对该控件中的属性使用属性绑定
例如
<input type="text" formControlName="xyz" [readonly]="anyBooleanPropertyFromComponent" />
对于reactive-forms,如果您想将字段设为只读,一种方法是使用普通的旧 javascript:
(document.getElementById('abc') as HTMLInputElement).setAttribute('readonly','true');
Run Code Online (Sandbox Code Playgroud)
除此之外,您还可以将代码转换为更多的打字稿和角度方式。使用@ViewChild访问的元素,然后将设置readonly属性为true:
HTML
<input [formControl]='data' id='abc' #element [readonly]="data.disabled"/>
Run Code Online (Sandbox Code Playgroud)
TS
@ViewChild('element',{static:true, read: ElementRef}) element : ElementRef ;
(this.element.nativeElement as HTMLInputElement).readOnly = true;
Run Code Online (Sandbox Code Playgroud)
但是,您需要在修改 readonly 属性之前检查 formControl 的状态。
| 归档时间: |
|
| 查看次数: |
38709 次 |
| 最近记录: |