In my angular2 app i'd like to have a reusable select component which, in a first draft, looks like this:
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);
}
}
Unfortunately, this works only with an Array of strings as Input Parameter, since
{{ opt }}
would only print out [Object object] for other types. And thus, the EventEmitter will only emit strings.
Now, what I'd like to have is a component, that I can use similar like this:
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 intentions:
- tell the
my-selectcomponent, that the shown values should be theuserFriendlyStringproperty ofFoo. I don't want to hardcode that, since other components should be able to usemy-selectas well with other model classes. I can't imagine how to do that. My first Approach was to have a callback function as@Input()for themy-selectcomponent, but that doesn't work and shouldn't be done according to this answer. The second Approach was to override toString inFoo. Doesn't work neither (I assume something like missing dynamic dispatch inany...?!). - get the
EventEmitterwork as 'expected': it should be possible to have a correctfoo: Fooin the handle function.
So, is there hope for me? :)