angular - 如何从角度动态构建中获取表单控件值
问题描述
在这里,我将一些数据从父组件传递到子组件以构建动态表单。
这是我的父组件 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
.
解决方案
您可以通过 @Input 传递 parentForm 然后分配 formGroup
在子组件 ngOnInit 中,您可以添加this.parentForm.addControl('childGroup', myGroup)
亲子形式组合游乐场: stackblitz游乐场
推荐阅读
- mysql - MySQL 集群是否支持协调节点?
- firebase - GeneratedPluginConstraint,致命错误:找不到模块“firebase_auth”@import firebase_auth;
- machine-learning - jupyter notebook:运行单元不起作用
- javascript - rxfire 订阅未在 componentdidmount 中触发
- json - 条件jq提取层次结构不同位置的两个元素
- go - 在绑定到特定的 127.xxx 地址时侦听多播环回
- html - 我试图让一个按钮转到另一个页面,但它不起作用
- python - 将字节字符串拆分为列
- azure - 是否可以使用站点到站点 (VPN) 连接来连接两个 Azure VNet?
- db2 - 在okd上部署db2