【发布时间】:2017-11-01 01:19:41
【问题描述】:
注意:由于problem is a little complex,代码被抽象为可读性
我们有一个像这样的<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?
}
}
- 它是 Angular 2 中 output configuration 的正确实现吗?
- 我们如何从
<parent-component>的form提交到submit(f)函数的<child-component>访问select的option的值?
【问题讨论】:
-
childEvent必须是someChildEvent -
@echonax 绝对正确,但是我们如何在
submit(f)函数中获取<child-component>的select元素的值? -
那可能是因为
[ngValue]="a.key"所以a.key是0我猜?它会使用[ngValue]="a"发送整个对象 -
只是一个建议,不要在@Component 注释中使用
outputs属性,而是在someChildEvent 属性上使用@Output 注释,如下所示:@Output() someChildEvent = new EventEmitter<string>(); -
它将使您的代码更具可读性和可维护性。例如,如果重构
someChildEvent属性的名称,则无需更新outputs中无法进行类型检查的字符串数组。
标签: javascript angular typescript output