我有一堆子元素包含form
-表单的值将从父子元素发送-我在父子对象中循环了子子元素并将数据传递给了子元素
子组件
<form #formType="ngForm">
<div class="col-lg-4" *ngFor="let data of productSizes; let i = index;">
<div class="inlinediv" *ngFor="let item of data.ItemDetails">
<div class="marginright15 inlinediv">
<ng-container *ngIf="item.Foundation">
<b>{{item.Size.toUpperCase()}}</b><br />
<input *ngFor="let val of item.Foundation" type="text" appNumbericInput maxlength="4" [(ngModel)]="val.Val" class="inputcustom text-right" [disabled]="(val.Val == null ? true : false) || disableChecker" (input)="enableSave=true" />
</ng-container>
</div>
</div>
</div>
</form>
子Component.ts
@Component({
selector: 'app-base-mattress',
templateUrl: './base-mattress.component.html',
styleUrls: ['./base-mattress.component.css']
})
export class BaseMattressComponent implements OnInit {
@Input() productSizes: IItemDetails[];
@ViewChild('formType') formVariable: NgForm;
blobURL: string = environment.blobURL;
constructor() {}
ngOnInit() {}
}
父组件html
<ng-container *ngFor="let slot of slotRequests; let j = index;">
<ng-container *ngIf="slot.ItemGrouping.toLowerCase() === 'mattress'">
<ng-container *ngFor="let data of slotRequests[j].Data; let i = index;">
<app-base-mattress [productSizes]="data"></app-base-mattress>
</ng-container>
</ng-container>
</ng-container>
现在我的问题是我想读取子组件的表单变量?
我不想订阅某个服务,并检查form
是否脏了,我已经尝试了很多次,但都没用。
我试图用这样的模板引用变量来映射我的孩子
<app-base-mattress [productSizes]="data" #childData></app-base-mattress>
但似乎我正在循环子组件,因此它似乎不充当特定组件的参考变量-请帮助我找出如何读取子组件形式变量
StackBlitz的工作版本
谢谢!
答案 0 :(得分:1)
在顶级组件中使用表单元素
<form #formType="ngForm">
<ng-container *ngFor="let slot of slotRequests; let j = index;">
<ng-container *ngIf="slot.ItemGrouping.toLowerCase() === 'mattress'">
<ng-container>
<div *ngFor="let data of slotRequests[j].Data; let i = index;">
<app-base-mattress [productSizes]="data.ItemDetails"></app-base-mattress>
</div>
</ng-container>
</ng-container>
</ng-container>
</form>
使用viewproviders提供controncontainer,它是form的超类。将现有的ngForm组组一起用于表单
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NgForm, ControlContainer } from '@angular/forms'
@Component({
selector: 'app-base-mattress',
templateUrl: './base-mattress.component.html',
styleUrls: ['./base-mattress.component.css'],
viewProviders: [{ provide: ControlContainer, useExisting: NgForm }]
})
export class BaseMattressComponent implements OnInit {
@Input() productSizes: any[];
constructor() { }
ngOnInit() {
}
}
答案 1 :(得分:0)
您可以这样做:
parent.component.html :
<app-base-mattress #childCmp [productSizes]="data"></app-base-mattress>
parent.component.ts :
@ViewChildren('childCmp ')
childCmps: QueryList<BaseMattressComponent>;
然后遍历它们以获得所需的结果
this.childCmps.forEach((item) => {
...
});