我正在用反应形式构建角6中的形式,并且我正在为每个部分使用组件,我遇到了一些问题:如何在父组件中使用方法的子组件中使用FormArray。例如:
在父ts文件中:
constructor(private fb: FormBuilder,
private http: Http) { }
ngOnInit() {
this.parentForm = this.fb.group({
_server: this.fb.array([this.initItemRows()]),
})
}
initItemRows() {
return this.fb.group({
// DocumentID: uuid(),
HostName: [],
IPAddress: [],
Domain: [],
OS: []
});
}
get serverForms() {
return this.parentForm.get('_server') as FormArray
}
addServer() {
const server = this.fb.group({
// DocumentID: uuid(),
HostName: [],
IPAddress: [],
Domain: [],
OS: []
})
this.serverForms.push(server);
}
deleteServer(i) {
this.serverForms.removeAt(i)
}
在父html中我有:
<div formArrayName="_server">
<table id="_server" class="table table-striped table-bordered">
<thead>
<tr>
<th>Host name</th>
<th>IP</th>
<th>Domain</th>
<th>OS</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let server of serverForms.controls; let i=index" [formGroupName]="i">
<td>
<input formControlName="HostName" class="form-control" type="text" />
</td>
<td>
<input formControlName="IPAddress" class="form-control" type="text" />
</td>
<td>
<input formControlName="Domain" class="form-control" type="text" />
</td>
<td>
<input formControlName="OS" class="form-control" type="text" />
</td>
<td class="buttonCenter">
<button mat-raised-button color="primary" class="deleteFieldButton" (click)="deleteServer(i)" type="button">delete</button>
</td>
</tr>
</tbody>
<button mat-raised-button color="primary" class="addFieldButton" (click)="addServer()" type="button">insert row</button>
</table>
</div>
但是我想使用父(上面(的所有html代码在子组件中
<app-servers-section></app-servers-section>
我知道我可以在子组件中使用FormGroupDirective,但当我需要使用parents方法时,它不起作用。
请给我建议!谢谢
您需要这样做。
<app-servers-section (changeInChildForm)="doSomething($event)"></app-servers-section>
在要保存窗体的子组件中,需要从那里发出一个事件。
因此,在您的ChildComponent.ts中,使用Component和其他导入EventEmitter和Output
import { Component, EventEmitter, Input, Output } from '@angular/core';
在类的主体中,您可以执行类似的操作来从子对象发出要传递给父对象的事件。
@Output() changeInChildForm = new EventEmitter<boolean>();
somethingHappenedInChild(data: any) {
this.changeInChildForm.emit(data);
}
因此,当您想要从子级发出更改时,请调用子组件的方法somethingHappenedInChild
。将发出changeInChildForm
,它将调用Parent组件的方法doSomething($event)
。
我没有创建stackblitz。但是,如果您想要更多关于这方面的帮助,请创建一个前面提到的stackblitz。