main.component.html
<form (ngSubmit)="onSubmit()" #formData="ngForm" />
<input type="text" ngModel name="firstName" />
<div class="row" [ngSwitch]="type">
<div *ngSwitchCase="'Employee'" class="col-sm-9 col-md-10">
<app-employee></app-employee>
</div>
<div *ngSwitchCase="'Customer'" class="col-sm-9 col-md-10">
<app-customer></app-customer>
</div>
</div>
<input type="submit" value="Save" />
</form>
main.component.ts
@ViewChild('formData') formData: NgForm;
onSubmit(){
console.log(formData.value);
}
employee.component.html:
<input type="text" class="form-control" ngModel name="Address"/>
只能获取firstname值,但不能从employee.component.html获取任何值。
在这种情况下,根据情况将更改模板内容,并且不同的模板具有其自己的不同控件。
我是否需要以其他方式处理这种情况,或者我用来读取表单数据的方式是错误的?
答案 0 :(得分:0)
您需要为每个子组件创建一个模型对象,或者使用来自parent => child的@input传递模型对象。您可以在提交时访问父组件中的模型对象值。
答案 1 :(得分:0)
您需要将数据从子组件发送到父组件,然后使用发出的值填充相关的formData。您可以执行以下操作:
employee.component.html:
<input type="text" class="form-control" [(ngModel)]="employee" />
employee.component.ts:
@Output() onEmployeeEntered = new EventEmitter<string>();
employee: string;
employeeChanged = () => {
this.onEmployeeEntered.emit(this.employee);
}
main.component.html:
<app-employee (onEmployeeEntered)="onEmployeeEntered(employee)"></app-employee>
main.component.ts:
onEmployeeEntered = (employee) => {
// add the employee to form data
// let's say you have form data stored in form variable.
// You can do something like this.
this.form.patchValue({
'employee': employee
});
}