Skip to content

Instantly share code, notes, and snippets.

@BPagoaga
Last active February 25, 2019 11:06
Show Gist options
  • Save BPagoaga/dd51c12898c06578866687743802ab41 to your computer and use it in GitHub Desktop.
Save BPagoaga/dd51c12898c06578866687743802ab41 to your computer and use it in GitHub Desktop.
How to force all parents of a component to implement an interface
<app-child-component></app-child-component>
import { Component, OnInit } from "@angular/core";
import { TestInterface } from "./test-interface";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit, TestInterface {
title = "app";
isAuth = false;
constructor() {
setTimeout(() => {
this.isAuth = true;
}, 4000);
}
ngOnInit() {}
// if this method is not present, an exception will be thrown
testMethod() {
console.log('test method')
}
}
import { Component, OnInit, Host } from "@angular/core";
import { AppComponent } from "../app.component";
import { TestInterface } from "../test-interface";
const TestInterface = {
// list all the property and methods of the TestInterface type
// as the type itself is not iterable
testMethod() {}
}
@Component({
selector: "app-child-component",
templateUrl: "./child-component.component.html",
styleUrls: ["./child-component.component.scss"]
})
export class ChildComponentComponent implements OnInit {
constructor(@Host() host: AppComponent) {
// makes sure the parent implements the interface
Object.keys(TestInterface).forEach(method => {
if (!Object.getPrototypeOf(host).hasOwnProperty(method)) {
throw `The class ${Object.getPrototypeOf(host).constructor.name} must implements the method ${method}`;
}
})
}
ngOnInit() {}
}
export interface TestInterface {
testMethod();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment