在我的 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组件,显示的值应该userFriendlyString是Foo. 我不想硬编码,因为其他组件也应该能够my-select与其他模型类一起使用。我无法想象该怎么做。我的第一个方法是为@Input()组件设置一个回调函数my-select,但这不起作用,不应该根据这个答案来完成。第二种方法是覆盖 toString inFoo。也不起作用(我假设在any...中缺少动态调度?!)。 - 得到
EventEmitter“预期”的工作:应该可以foo: Foo在句柄函数中有一个正确的。
那么,我还有希望吗?:)