sam*_*990 3 components angular2-forms angular
我有通过表单构建器构建的组件,现在在该表单中我需要包含一个只有一个输入框作为表单控件的组件.
add.ts
this.newForm = this.fb.group({
name: ['', [Validators.required]],
surname:['', [Validators.required]],
time: ''
});
Run Code Online (Sandbox Code Playgroud)
"时间"必须作为一个不同的组成部分.
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>
Run Code Online (Sandbox Code Playgroud)
为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>
Run Code Online (Sandbox Code Playgroud)
如何将表单控件"time"作为主窗体中的一个组件包含在内,这样我就可以通过this.newForm.controls ['time']访问该值.
单个Form Control不能单独传递给子组件,它必须在一个内部传递formGroup.因此timeGroup,在表单中添加一个组(此处命名):
this.newForm = this.fb.group({
name: ['', [Validators.required]],
surname:['', [Validators.required]],
timeGroup: this.fb.group({
time: ''
})
});
Run Code Online (Sandbox Code Playgroud)
在您的父html传递formGroup给您的孩子:
<time-comp [timeGroup]="newForm.controls.timeGroup"></time-comp>
Run Code Online (Sandbox Code Playgroud)
和儿童模板:
<div [formGroup]="timeGroup">
<input formControlName="time">
</div>
Run Code Online (Sandbox Code Playgroud)
并且不要忘记将从父级收到的表单组标记为Input:
@Input() timeGroup: FormGroup;
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下命令访问该time值(在您的父级中):
this.newForm.get('timeGroup').get('time').value;
Run Code Online (Sandbox Code Playgroud)
另请注意,您不需要任何事件,例如keyup,没有它们的父级将捕获更改.
| 归档时间: |
|
| 查看次数: |
878 次 |
| 最近记录: |