简体   繁体   English

Angular 扩展父组件 HTML

[英]Angular extends parent component HTML

I know this is an old question but I cant find a simple answer and it seems so strange.我知道这是一个老问题,但我找不到简单的答案,而且看起来很奇怪。

I have a father component with its own html and several component that extends this one.我有一个父组件,它有自己的 html 和几个扩展这个组件的组件。

I need something like this:我需要这样的东西:

Father's HTML template父亲的HTML模板

<p class="father"> somethings </p>
<child-component></child-component> <-- some kind of angular tag

class ChildComponent extends FatherComponent class ChildComponent 扩展了 FatherComponent

<p> Im a Child </p>

Result rendering Child结果渲染子

<p class="father"> somethings </p>
<p> Im a Child </p>

Is this so hard to get?这有那么难得到吗?

UPDATE AS ASKED按要求更新

@Component({
    selector: 'BaseComponent',
    templateUrl: 'BaseComponent.html',
})
export class BaseComponent implements OnInit 
{
...
}



@Component({
    selector      : 'ChildBaseComponent ',
    templateUrl   : 'ChildBaseComponent .html',
  })
export class ChildBaseComponent extends BaseComponent
{
   ....
}

I think what you're looking for here is content projection .我认为您在这里寻找的是内容投影 You can find plenty of articles about this topic.你可以找到很多关于这个主题的文章。 I modified you examples slightly我稍微修改了你的例子

@Component({
    selector: 'BaseComponent',
    template: `
               <p class="father"> somethings </p>
               <ng-content></ng-content>
               `,
})
export class BaseComponent implements OnInit 
{
...
}



@Component({
    selector      : 'ChildBaseComponent',
    templateUrl   : `
                      <BaseComponent><p> Im a Child </p></BaseComponent>`,
  })
export class ChildComponent
{
@ViewChild(BaseComponent) public baseComponent: BaseComponent
   
}

The thing is Angular doesn't inherit metadata of the parent class, it overrides it.问题是 Angular 不继承父 class 的元数据,它会覆盖它。 There plenty of tools angular provides to deal with code sharing. angular 提供了很多工具来处理代码共享。 You can always access your parent component from the child thanks to ViewChild decorator.借助 ViewChild 装饰器,您始终可以从子组件访问您的父组件。 And as the answer to your question - no, there is no such tag.作为您问题的答案 - 不,没有这样的标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM