【发布时间】:2021-12-20 15:38:29
【问题描述】:
在这里,我将一些数据从父组件传递到子组件以构建动态表单。
这是我的父组件html
<app-child-com *ngIf="info.length>0" #FormFieldValues [info]="info"
[provider] = "provider"></app-child-com>
这是我的父 component.ts 文件
@ViewChild('FormFieldValues', {static: false}) formConfigValues: ChildComComponent;
setInfo(){
this.service.getDetails().subscribe(res => {
this.info = res;
}, err => {
console.log(err);
});
}
我正在尝试访问从子组件到父组件的传递数据。
saveDetails(){
console.log(this.formConfigValues.Id);
}
这是我的子组件.ts
ngOnChanges(changes: SimpleChanges): void {
if (this.info.length > 0 || this.info !== undefined) {
this.createForm();
}
}
private createForm() {
const group = {};
this.info.forEach(field => {
if (field.type === 'text') {
group[field.name] = new FormControl('', Validators.required);
if (group[field.name] === 'id') {
if (this.configFieldForm.get('id').value != null || this.configFieldForm.get('id').value != undefined) {
this.Id = this.configFieldForm.get('id').value;
console.log(this.Id);
}
}
if (group[field.name] === 'key') {
if (this.configFieldForm.get('key').value != null || this.configFieldForm.get('key').value != undefined) {
this.Key = this.configFieldForm.get('key').value;
console.log(this.Key);
}
}
}
});
this.configFieldForm = new FormGroup(group);
}
这是我的子组件html文件
<form [formGroup]="configFieldForm" >
<div [isOpen]="isLiveOpen" [isDisabled]="isLiveDisabled" class="mb-3">
<ng-container *ngFor="let field of info">
<div class="row">
<div class="col-12">
<ng-template [ngIf]="field.type === 'heading'">
<div class="col-sm-12">
<h6>{{field.label}}</h6>
</div>
</ng-template>
<ng-template [ngIf]="field.type === 'text'">
<div class="form-group row">
<div class="col-sm-4">
<label class="col-form-label">{{field.label}}
<ng-template [ngIf]="field.required === true">
<span class="required-asterisk">*</span>
</ng-template>
</label>
</div>
<div class="col-sm-8">
<div class="custom-file">
<input type="text" class="form-control" placeholder="{{field.label}}"
formControlName="{{field.name}}">
</div>
</div>
</div>
</ng-template>
</div>
</div>
</ng-container>
</div>
</form>
但我无法在父组件console.log(this.formConfigValues.Id) 中访问此值如何获取用户在子组件文本框中输入的值并将其传递给父组件。目前它以undefined 的形式出现。
【问题讨论】:
标签: angular angular-reactive-forms form-control angular-formbuilder