Create a dropdown component

前端 未结 6 1431
我寻月下人不归
我寻月下人不归 2020-12-08 15:39

I want to create a dropdown menu using Angular 2, but I\'m not sure how to do it in the \"Angular 2 way\".

I could create a dropdown component that is used like this

6条回答
  •  余生分开走
    2020-12-08 16:00

    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: `
        
    • {{value.label}}
    ` }) 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:

    
    

    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: `
        
    • {{value.label}}
    ` }) 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:

    
    

    Notice that the action method is the one of the parent component (not the dropdown one).

提交回复
热议问题