Last active
May 9, 2016 14:41
-
-
Save braindroplabs/df9399d9191473b3c8108590e143a588 to your computer and use it in GitHub Desktop.
I have a SelectableDirective that I place on distinct elements. How can I use @ViewChild to get the directives by name/alias (#header and #body below) vs getting the element the directive is on?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, EventEmitter, Input, Output } from '@angular/core'; | |
@Directive({ | |
selector: '[selectable]', | |
host: { | |
'(click)': 'onClick()' | |
} | |
}) | |
export class SelectableDirective { | |
el; | |
@Input() isSelected: Boolean; | |
@Output() isSelectedChange: EventEmitter<any> = new EventEmitter(); | |
constructor(el: ElementRef) { | |
this.el = el.nativeElement; | |
} | |
select() { | |
this.isSelected = true; | |
} | |
deselect() { | |
this.isSelected = false; | |
} | |
private onClick() { | |
this.isSelected = !this.isSelected; | |
this.isSelectedChange.emit(this); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div selectable #header (isSelectedChange)="onIsSelectedChange($event)"> | |
<p>Header</p> | |
</div> | |
<div selectable #body (isSelectedChange)="onIsSelectedChange($event)"> | |
<p>Body</p> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Input, ViewChild } from '@angular/core'; | |
import { SelectableDirective } from '../../shared/directives/selectable.directive'; | |
@Component({ | |
moduleId: module.id, | |
selector: 'app-text-select', | |
templateUrl: 'text-select.component.html', | |
styleUrls: ['text-select.component.css'], | |
directives: [SelectableDirective] | |
}) | |
export class TextSelectComponent { | |
@Input() canAddQuotes: Boolean = false; | |
@ViewChild('header') selectableHeader: SelectableDirective; | |
@ViewChild('body') selectableBody: SelectableDirective; | |
onIsSelectedChange($event) { | |
let method = $event.isSelected ? 'add' : 'remove'; | |
$event.el.classList[method]('selected'); | |
if($event === this.selectableBody) { | |
this.canAddQuotes = $event.isSelected; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment