Skip to content

Instantly share code, notes, and snippets.

@braindroplabs
Last active May 9, 2016 14:41
Show Gist options
  • Save braindroplabs/df9399d9191473b3c8108590e143a588 to your computer and use it in GitHub Desktop.
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?
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);
}
}
<div selectable #header (isSelectedChange)="onIsSelectedChange($event)">
<p>Header</p>
</div>
<div selectable #body (isSelectedChange)="onIsSelectedChange($event)">
<p>Body</p>
</div>
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