包括一个组件作为FormControl Angular2 [英] Include a component as FormControl Angular2
问题描述
我有一个通过表单构建器构建的表单组件,现在在该表单中,我需要包含一个只有一个输入框作为表单控件的组件.
I have component that has form built through form builder and now in that form i need to include a component that has only one input box as a form control.
add.ts
this.newForm = this.fb.group({
name: ['', [Validators.required]],
surname:['', [Validators.required]],
time: ''
});
时间"必须作为一个不同的组成部分包括在内.
"time" has to be included as a different component.
add.html
<div class="form-group">
<label class="col-md-3 control-label" for="name">{{'forms.newForm.label.configuration.name' | translate}}</label>
<div class="col-md-3">
<input type="text" formControlName="name" placeholder="placeholder"
class="form-control input-md" type="text">
<small *ngIf="!newForm.controls.name.valid && newForm.controls.name.dirty" class="text-danger">
Name is required.
</small>
</div>
<label class="col-md-3 control-label" for="surname">{{'forms.newForm.label.configuration.name' | translate}}</label>
<div class="col-md-3">
<input type="text" formControlName="surname" placeholder="placeholder"
class="form-control input-md" type="text">
<small *ngIf="!newForm.controls.surname.valid && newForm.controls.name.dirty" class="text-danger">
Surname is required.
</small>
</div>
</div>
time.html
time.html
<div>
<div class="col-md-7">
<input class="form-control input-md" type="text" (keydown)="eventHandler($event)" maxlength="11">
<small *ngIf="!validTime" class="text-danger">
Invalid time
</small>
</div>
</div>
我如何将表单控件时间"作为主要表单的组成部分包含在内,以便我可以通过this.newForm.controls ['time'].value?
How to i include form control "time" as a component in the main form so i can access the value through this.newForm.controls['time'].value??
推荐答案
单个Form Control
不能单独传递给子组件,必须在formGroup
中传递.因此,在您的表单中添加一个组(此处为timeGroup
):
A single Form Control
cannot be passed separately to the child component, it has to be passed within a formGroup
. So add a group (here named timeGroup
) to your form:
this.newForm = this.fb.group({
name: ['', [Validators.required]],
surname:['', [Validators.required]],
timeGroup: this.fb.group({
time: ''
})
});
在您的父html中将formGroup
传递给您的孩子:
In your parent html pass the formGroup
to your child:
<time-comp [timeGroup]="newForm.controls.timeGroup"></time-comp>
和子模板:
<div [formGroup]="timeGroup">
<input formControlName="time">
</div>
并且不要忘记用Input
标记从父级收到的表单组:
And do not forget to mark the formgroup received from parent with Input
:
@Input() timeGroup: FormGroup;
然后,您可以通过以下方式访问time
值(在您的父级中):
Then you can access the time
value (in your parent) with:
this.newForm.get('timeGroup').get('time').value;
还请注意,您不需要任何事件,例如keyup
,更改将由没有它们的父级捕获.
Also notice that you do not need any events, like keyup
, the changes will be catched by the parent without them.
这篇关于包括一个组件作为FormControl Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!