我有一个使用子窗体组件的父窗体组件。我正在使用Angular反应形式。我的验证器功能正常运行,但是问题是,在加载表单时,子表单组件已被标记为已触摸,这弄乱了我的验证器功能:
this.editUserForm = this.fb.group ({
phone: ['123-456-1234'],
fax: [null],
email: [null],
website: [null],
editUserForm_Address : this.fb.group ({
address1: ['123 Elm Street', Validators.required],
address2: [null],
city: ['Dummy City', Validators.required],
state: ['Dummy State', Validators.required],
zipcode: ['11111', Validators.required],
country: ['USA', Validators.required]
})
});
父组件html使用子组件:
<form [formGroup] = "editUserForm">
<address-form formGroupName = "editUserForm_Address"></address-form>
</form>
子组件类如下:
export class AddressFormComponent implements OnInit {
public addressFormGroup: FormGroup;
@Input()
constructor(private controlContainer: ControlContainer) { }
ngOnInit() {
this.addressFormGroup = <FormGroup>this.controlContainer.control;
}
}
子组件html如下(示例仅以地址1为例):
<ng-container [formGroup] = "addressFormGroup">
<div class = "row">
<div class = "form-group col-12" [ngClass]="{'error': (addressFormGroup.controls['address1'].errors)">
<label for="street" >Address 1*</label>
<input placeholder = "Address 1" class="form-control" formControlName="address1">
<div *ngIf="(addressFormGroup.controls['address1'].errors)" class="error-msg">
<div [hidden]="!addressFormGroup.controls['address1'].errors.required"
class = "input_feedback">Address 1 is required.</div>
</div>
</div>
我尝试过的方法: 我尝试过使用生命周期挂钩,例如ngAfterViewInit()来将子formGroup标记为未触摸,但是ngAfterViewInit()执行后会加载表单,并且子formGroup仍被标记为已触摸。
答案 0 :(得分:1)
您需要做的就是将表单组传递给子级,并在模板中显示该表单组。因此,只需标记为@Input
就可以了:)
<address-form
[editUserForm_Address]="editUserForm.get('editUserForm_Address')">
</address-form>
然后在孩子身上,只需标记:
@Input() editUserForm_Address: FormGroup;
在模板中,我建议使用get()
来设置表单域,并建议hasError()
来检查表单组上的错误,以使模板更具可读性:)
<ng-container [formGroup]="editUserForm_Address">
<label for="street">Address 1*</label>
<input placeholder="Address 1" formControlName="address1">
<div *ngIf="editUserForm_Address.get('address1').errors">
<div [hidden]="!editUserForm_Address.hasError('required','address1')">
Address 1 is required.
</div>
</div>
</ng-container>
示例 StackBlitz