I would say that it depends on what you want to do.
If your dropdown is a component for a form that manages a state, I would leverage the two-way binding of Angular2. For this, I would use two attributes: an input one to get the associated object and an output one to notify when the state changes.
Here is a sample:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="select(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Input()
value: string[];
@Output()
valueChange: EventEmitter;
constructor(private elementRef:ElementRef) {
this.valueChange = new EventEmitter();
}
select(value) {
this.valueChange.emit(value);
}
}
This allows you to use it this way:
<dropdown [values]="dropdownValues" [(value)]="value"></dropdown>
You can build your dropdown within the component, apply styles and manage selections internally.
Edit
You can notice that you can either simply leverage a custom event in your component to trigger the selection of a dropdown. So the component would now be something like this:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="selectItem(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Output()
select: EventEmitter;
constructor() {
this.select = new EventEmitter();
}
selectItem(value) {
this.select.emit(value);
}
}
Then you can use the component like this:
<dropdown [values]="dropdownValues" (select)="action($event.value)"></dropdown>
Notice that the action
method is the one of the parent component (not the dropdown one).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…