|
| 1 | +// #docplaster |
| 2 | +// #docregion |
| 3 | +import { Component } from '@angular/core'; |
| 4 | +import { ContentChild } from '@angular/core'; |
| 5 | +import { EventEmitter } from '@angular/core'; |
| 6 | +import { Input } from '@angular/core'; |
| 7 | +import { Output } from '@angular/core'; |
| 8 | +import { TemplateRef } from '@angular/core'; |
| 9 | + |
| 10 | +interface ItemContext { |
| 11 | + item: any; |
| 12 | + index: number; |
| 13 | +} |
| 14 | + |
| 15 | +// #docregion component |
| 16 | +// #docregion metadata |
| 17 | +@Component({ |
| 18 | + selector: 'simple-select', |
| 19 | + template: |
| 20 | + ` |
| 21 | + <button (click)='toggleItems()' class='select-root'> |
| 22 | + |
| 23 | + <template |
| 24 | + [ngTemplateOutlet]='itemTemplateRef' |
| 25 | + [ngOutletContext]='{ item: value, index: -1 }'> |
| 26 | + </template> |
| 27 | +
|
| 28 | + </button> |
| 29 | + |
| 30 | + <ul *ngIf='isShowingItems' class='select-items'> |
| 31 | + <li *ngFor='let item of items ; let index = index ;' (click)='selectItem( item )'> |
| 32 | + |
| 33 | + <template |
| 34 | + [ngTemplateOutlet]='itemTemplateRef' |
| 35 | + [ngOutletContext]='{ item: item, index: index }'> |
| 36 | + </template> |
| 37 | +
|
| 38 | + </li> |
| 39 | + </ul> |
| 40 | + ` |
| 41 | +}) |
| 42 | +// #enddocregion metadata |
| 43 | +export class SimpleSelectComponent { |
| 44 | + |
| 45 | + public isShowingItems: boolean; |
| 46 | + @Input() public items: any[]; |
| 47 | + public itemTemplateRef: TemplateRef<ItemContext>; |
| 48 | + @Input() public value: any; |
| 49 | + @Output() public valueChange: EventEmitter<any>; |
| 50 | + |
| 51 | + constructor() { |
| 52 | + this.isShowingItems = false; |
| 53 | + this.items = []; |
| 54 | + this.itemTemplateRef = null; |
| 55 | + this.value = null; |
| 56 | + this.valueChange = new EventEmitter(); |
| 57 | + } |
| 58 | + |
| 59 | + // #docregion setters |
| 60 | + @Input() |
| 61 | + set template( newTemplate: TemplateRef<ItemContext> ) { |
| 62 | + if ( newTemplate ) { |
| 63 | + this.itemTemplateRef = newTemplate; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + @ContentChild( TemplateRef ) |
| 68 | + set contentChildTemplateRef( newTemplate: TemplateRef<ItemContext> ) { |
| 69 | + if ( newTemplate ) { |
| 70 | + this.itemTemplateRef = newTemplate; |
| 71 | + } |
| 72 | + } |
| 73 | + // #enddocregion setters |
| 74 | + |
| 75 | + public selectItem( item: any ): void { |
| 76 | + this.valueChange.emit( item ); |
| 77 | + this.toggleItems(); |
| 78 | + } |
| 79 | + |
| 80 | + public toggleItems(): void { |
| 81 | + this.isShowingItems = ! this.isShowingItems; |
| 82 | + } |
| 83 | + |
| 84 | +} |
| 85 | +// #enddocregion component |
0 commit comments