我有以下问题。Click to check the stack blitz。
我在构造函数中设置了一个反应式表单:
this.formGroup = this.fb.group({
'family_name_en': new FormControl('', Validators.required),
'family_name_ar': new FormControl('', [Validators.required, Validators.pattern('[\u0600-\u06FF ]*')]),
'unit_id': new FormControl({ value: '', disabled: true }, [Validators.required])
});在ngOnInti()钩子中,我获得了与unit_id相关的数据。
由于我正在将数据从一个平台迁移到另一个平台,所以不推荐使用阿拉伯语的姓氏,但现在建议使用它。因此,大多数数据将在加载时不使用阿拉伯名称。
问题是按钮总是启用的,我需要做的是,如果用户想要更新这个unit_id,他应该添加阿拉伯名字,这样按钮就会启用。
如果表单有效,则在加载组件时启用按钮无伤大雅。
下面是获取数据并设置表单组控件值的getData()方法:
ngOnInit() {
this.getDataById();
}getDataById():
getDataById() {
this.showSpinner = true;
this.auth.getDataById(this.unit_id).subscribe(
(data) => {
if (data['info'][0]['total'] == 1) {
this.noDataBool = false;
this.showSpinner = false;
this.family_name_en = data['info'][0]['hh_last_name_en'];
this.formGroup.controls['family_name_en'].setValue(this.family_name_en);
this.family_name_ar = data['info'][0]['hh_last_name_ar'];
this.formGroup.controls['family_name_ar'].setValue(this.family_name_ar);
this.unit_id = data['info'][0]['unit_id'];
this.formGroup.controls['unit_id '].setValue(this.unit_id);
}
}按钮:
<button mat-raised-button color="warn" (click)="updateData()" [disabled]="!formGroup.valid">
<mat-icon>update</mat-icon>Update
</button>发布于 2018-11-20 15:58:28
您应该在FormControl上使用get应用编程接口,而不是使用formGroup上的controls直接访问它们。这将为您提供更多的控制并显著地清理您的实现(特别是在获得深度嵌套元素的情况下)。您可以像这样更改组件实现:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
formGroup: FormGroup;
titleAlert: string = 'This field is required';
post: any = '';
family_name_en;
family_name_ar;
unit_id;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.formGroup = this.fb.group({
'family_name_en': new FormControl('', Validators.required),
'family_name_ar': new FormControl('', [Validators.required, Validators.pattern('[\u0600-\u06FF ]*')]),
'unit_id': new FormControl({ value: '', disabled: true }, [Validators.required])
});
this.getDataById();
}
getDataById() {
let data: Array<any> = [
'Ali', '', '123'
]
this.family_name_en = data[0];
this.formGroup.get('family_name_en').setValue(this.family_name_en);
this.family_name_ar = data[1];
this.formGroup.get('family_name_ar').setValue(this.family_name_ar);
this.unit_id = data[2];
this.formGroup.get('unit_id').setValue(this.unit_id);
}
}这是你的裁判的。您可以通过在其中输入علي来测试它,这将启用更新按钮。键入Ali将使其保持禁用状态。
发布于 2018-11-20 15:11:52
在这样的情况下,我总是使用以下代码:
this.family_name_ar.setValue(data['info'][0]['hh_last_name_ar']);
this.family_name_ar.updateValueAndValidity();通过调用第二个方法updateValueAndValidity(),我们告诉Angular
重新计算控件的值和验证状态。
有关Angular Docs的更多信息。
现在,如果data['info'][0]['hh_last_name_ar']为空,则应禁用该按钮并使表单无效。
您可以对每个需要的字段使用上面的方法。
https://stackoverflow.com/questions/53387798
复制相似问题