Last active
February 25, 2019 11:06
-
-
Save BPagoaga/dd51c12898c06578866687743802ab41 to your computer and use it in GitHub Desktop.
How to force all parents of a component to implement an interface
This file contains hidden or 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
<app-child-component></app-child-component> |
This file contains hidden or 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, 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') | |
} | |
} |
This file contains hidden or 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, 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() {} | |
} |
This file contains hidden or 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
export interface TestInterface { | |
testMethod(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment