Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 extend base component

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() {
  }

}
like image 266
brazuka Avatar asked Mar 16 '18 12:03

brazuka


People also ask

Can we extend a component in Angular?

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.

Can we extend two components in Angular?

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.

Can a component extend a directive?

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.


1 Answers

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);
  }
*/
}
like image 139
Estus Flask Avatar answered Oct 20 '22 13:10

Estus Flask