Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Last active October 18, 2018 17:59
Show Gist options
  • Save NetanelBasal/f6b30506b542a39ae117bd969088da0b to your computer and use it in GitHub Desktop.
Save NetanelBasal/f6b30506b542a39ae117bd969088da0b to your computer and use it in GitHub Desktop.
@Component({
selector: 'connection',
template: `
<ng-template [ngTemplateOutlet]="fast.tpl" *ngIf="isFast"></ng-template>
<ng-template [ngTemplateOutlet]="slow.tpl" *ngIf="!isFast"></ng-template>
`,
})
export class ConnectionComponent {
isFast = true;
@ContentChild(FastDirective) fast: FastDirective;
@ContentChild(SlowDirective) slow: SlowDirective;
private subscription: Subscription;
ngOnInit() {
const connection = navigator.connection;
if (!connection) {
// if the browser doesn't support it, we render the fast template
return;
}
this.subscription = connection$
.subscribe((effectiveType: string) => {
if (/\slow-2g|2g|3g/.test(effectiveType)) {
this.isFast = false;
} else {
this.isFast = true;
}
})
}
ngOnDestroy() {
this.subscription && this.subscription.unsubscribe();
}
}
@Directive({
selector: '[fast]'
})
export class FastDirective {
constructor(public tpl: TemplateRef<any>) { }
}
@Directive({
selector: '[slow]'
})
export class SlowDirective {
constructor(public tpl: TemplateRef<any>) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment