I have a Base Component which is extended by its childs, but when we create a new Component in Angular using angular-cli it creates html and css files, but I will not use these files from base component.
Is there a way to create a Base Component without html and css?
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-base',
templateUrl: './base.component.html', //I dont need this
styleUrls: ['./base.component.css'] ////I dont need this
})
export class BaseComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
import { Component } from '@angular/core';
import { BaseComponent } from '../base/base.component';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent extends BaseComponent {
constructor() {
super();
}
ngOnInit() {
}
}
Inheritance with Angular Components This same concept can be applied to Angular components. We can create a “parent” component with common properties/functions, followed by a child component that “extends” the parent.
If the abstract class extended by two or more components contains shared logic: use a service or even create a new typescript class that can be shared between the two components.
Directives are what the Open-Closed Principle is about. The component is closed for modifications, but a directive allows you to extend the component without changing the internals.
Since base class doesn't need to be instantiated on its own, it's abstract class and doesn't need to have @Component
decorator.
If it has dependencies, and there's a chance that constructor
will be omitted in child classes and inherited, base class should have @Injectable
decorator:
@Injectable()
export abstract class BaseComponent implements OnInit {
constructor(public dep: Dep) {}
ngOnInit() {}
}
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent extends BaseComponent {
// dummy constructor can be omitted
/*
constructor(dep: Dep) {
super(dep);
}
*/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With