Skip to content

Instantly share code, notes, and snippets.

@jhades
Created May 12, 2016 08:00
Show Gist options
  • Save jhades/05abbea955550c640a62fe121e011da6 to your computer and use it in GitHub Desktop.
Save jhades/05abbea955550c640a62fe121e011da6 to your computer and use it in GitHub Desktop.
Angular 2 guided tour To Directives
@Component({
selector: 'app',
directives: [ShowOne, ShowOneContainer, ShowOneTrigger],
template: `
<div class="tab-container" showOneContainer>
<ul class="tab-buttons">
<li showOneTrigger="superman" [active]="true">Superman</li>
<li showOneTrigger="batman">Batman</li>
<li showOneTrigger="flash">Flash</li>
</ul>
<div class="tab-panel" showOne="superman" [active]="true">
<div class="logo superman"></div>
</div>
<div class="tab-panel" showOne="batman">
<div class="logo batman"></div>
</div>
<div class="tab-panel" showOne="flash">
<div class="logo flash"></div>
</div>
</div>
`
})
export class App {
}
bootstrap(App);
@Directive({
selector: '[showOneContainer]'
})
export class ShowOneContainer {
triggers: ShowOneTrigger[] = [];
@ContentChildren(ShowOne)
items: QueryList<ShowOne>;
add(trigger: ShowOneTrigger) {
this.triggers.push(trigger);
}
show(id:string) {
this.items.forEach(item => item.active = item.id == id);
this.triggers.forEach(
(trigger:ShowOneTrigger) => trigger.active = trigger.id == id);
}
}
@Directive({
selector: '[showOneTrigger]'
})
export class ShowOneTrigger {
@Input("showOneTrigger")
id: string;
@Input()
active = false;
constructor(private showOneContainer: ShowOneContainer) {
showOneContainer.add(this);
}
@HostListener('click')
click() {
this.showOneContainer.show(this.id);
}
@HostBinding('class.selected')
get selected() {
return this.active;
}
}
@Directive({
selector: '[showOne]'
})
export class ShowOne {
@Input("showOne")
id:string;
@Input()
active = false;
@HostBinding('hidden')
get hidden() {
return !this.active;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment