Note: since the problem is a little complex, the code is abstracted for readability
我们有一个 <child-component>
像这样的组件模板:
<select name="someName" #someID ngDefaultControl [(ngModel)]="someModel" (ngModelChange)="onChange(someID.value)">
<option *ngFor="let a of list" [ngValue]="a.key">{{a.value}}</option>
</select>
还有 ts
文件带有 output配置:
@Component({
moduleId: module.id,
selector: 'child-component',
templateUrl: 'child-component.html',
outputs: ['someChildEvent']
})
export class ChildComponent {
someChildEvent = new EventEmitter<string>();
onChange(value) {
this.someChildEvent.emit(value);
}
}
我们在 <parent-component>
中调用像这样:
<form #f="ngForm" (submit)="submit(f)" >
<child-component (childEvent)="childData=$event"></child-component>
<input type="submit" value="submit">
</form>
与 .ts
喜欢:
export class ParentComponent {
childData;
submit(f) {
//How to access childData here?
}
}
- 它是 output configuration 的正确实现吗?在 Angular 2 中?
- 我们如何访问
select
的值的option
来自<child-component>
在<parent-component>
的form
提交给submit(f)
功能?
最佳答案
<child-component (childEvent)="childData=$event"></child-component>
此处的事件名称需要与您的方法名称相匹配,因此它应该是:
<child-component (someChildEvent)="childData=$event"></child-component>
如果您想发送在选择框中选择的对象,请将 ngValue
更改为该对象并相应地更改模型事件:
[ngValue]="a"
(ngModelChange)="onChange($event)"
关于javascript - 在父组件的表单提交中获取子组件表单值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44281328/