注意:由于问题有点复杂,因此为了可读性,对代码进行了抽象
我们有一个<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
文件带有输出配置:
@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?
}
}
- 它是 Angular 2 中输出配置的正确实现吗?
- 我们如何从
<child-component>
访问select
option
的值<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)"