【发布时间】:2017-08-20 08:05:02
【问题描述】:
在我的 angular2 应用程序中,我希望有一个可重用的选择组件,在初稿中,它看起来像这样:
import {Component, Input, Output, EventEmitter} from "@angular/core";
@Component({
selector: 'my-select',
template: `
<select [(ngModel)]="selectedValue" (ngModelChange)="selectionChanged()">
<option disabled="disabled" selected="selected" name="choose" value="choose">choose ...</option>
<option *ngFor="let opt of selectModel" [ngValue]="opt">
{{opt}}
</option>
</select>
`
})
export class SelectComponent {
@Output()
changed: EventEmitter<any> = new EventEmitter();
@Input()
selectModel: any[] = [];
selectedValue: any = 'choose';
selectionChanged() {
this.changed.emit(this.selectedValue);
}
}
不幸的是,这仅适用于字符串数组作为输入参数,因为
{{ opt }}
只会为其他类型打印出[Object object]。因此,EventEmitter 只会发出字符串。
现在,我想要的是一个组件,我可以像这样使用它:
import {Component} from "@angular/core";
export class Foo {
bar: string;
id: number;
userFriendlyString: string = `id=${this.id}|bar=${this.bar}`;
constructor(bar: string, id: number) {
this.bar = bar;
this.id = id;
}
}
@Component({
template: `<my-select [selectModel]="model" (changed)="handle($event)"></my-select>`
})
export class AppComponent {
model: Foo[] = [new Foo('first', 1), new Foo('second', 2)];
handle(foo: Foo): void {/* ... */}
}
我的意图:
- 告诉
my-select组件,显示的值应该是Foo的userFriendlyString属性。我不想硬编码,因为其他组件应该能够使用my-select以及其他模型类。我无法想象该怎么做。我的第一个方法是为my-select组件设置一个回调函数为@Input(),但这不起作用,不应该这样做according to this answer。第二种方法是覆盖Foo中的 toString。也不起作用(我假设any中缺少动态调度...?!)。 - 让
EventEmitter工作为“预期”:应该可以在句柄函数中有一个正确的foo: Foo。
那么,我还有希望吗? :)
【问题讨论】:
标签: angular components ngmodel