在這里,我將一些資料從父組件傳遞到子組件以構建動態表單。
這是我的父組件 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);
}
這是我的孩子 component.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" >
<ng-container *ngFor="let field of info">
<div >
<div >
<ng-template [ngIf]="field.type === 'heading'">
<div >
<h6>{{field.label}}</h6>
</div>
</ng-template>
<ng-template [ngIf]="field.type === 'text'">
<div >
<div >
<label >{{field.label}}
<ng-template [ngIf]="field.required === true">
<span >*</span>
</ng-template>
</label>
</div>
<div >
<div >
<input type="text" placeholder="{{field.label}}"
formControlName="{{field.name}}">
</div>
</div>
</div>
</ng-template>
</div>
</div>
</ng-container>
</div>
</form>
但是我無法在父組件中訪問此值console.log(this.formConfigValues.Id)如何在子組件的文本框中獲取用戶鍵入的值并將其傳遞給父組件。目前它是作為undefined.
uj5u.com熱心網友回復:
您可以通過 @Input 傳遞 parentForm 然后分配 formGroup
在子組件 ngOnInit 中,您可以添加 this.parentForm.addControl('childGroup', myGroup)
親子形式組合游樂場: stackblitz游樂場
uj5u.com熱心網友回復:
console.log('Name:' this.userForm.get('name').value);
console.log('Age:' this.userForm.get('age').value);
console.log('City:' this.userForm.get('city').value);
console.log('Country:' this.userForm.get('country').value);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/352510.html
標籤:有角的 角反应形式 表单控制 angular-formbuilder
