typescript Angular 4 扩展基础组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49320759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:17:03  来源:igfitidea点击:

Angular 4 extend base component

angulartypescript

提问by brazuka

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.

我有一个由其子组件扩展的基础组件,但是当我们使用 angular-cli 在 Angular 中创建一个新组件时,它会创建 html 和 css 文件,但我不会使用基础组件中的这些文件。

Is there a way to create a Base Component without html and css?

有没有办法创建一个没有 html 和 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() {
  }

}

回答by Estus Flask

Since base class doesn't need to be instantiated on its own, it's abstract class and doesn't need to have @Componentdecorator.

由于基类不需要自己实例化,它是抽象类,不需要@Component装饰器。

If it has dependencies, and there's a chance that constructorwill be omitted in child classes and inherited, base class should have @Injectabledecorator:

如果它有依赖关系,并且有可能constructor在子类中被省略和继承,基类应该有@Injectable装饰器:

@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);
  }
*/
}