【发布时间】:2020-10-07 00:18:29
【问题描述】:
下面是一个组件,我将在其他各种组件中扩展它以重用一些代码..
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{appTitle}}</h1>
<div>To Tutorials Point</div>
</div> `,
})
export class AppComponent {
appTitle: string = 'Welcome';
ngOnInit(){
this.registerSomeSubscriptions();
}
registerSomeSubscriptions(){
this.subscribeSomething.subscribe((data)=>{
performSomeAction();
})
}
}
我可以像下面这样扩展它
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{appTitle}}</h1>
<div>To Tutorials Point</div>
</div> `,
})
export class ChildComponent extends AppComponent {
}
虽然我知道组件的公共成员将在子组件中可用。
我的问题
- 我是否仍然需要为这两个组件使用单独的 html 文件,或者他们的一些代码样式或解决问题的技术来重用相同的 html 模板以及通过一些我不知道的技术实现的一些子特定实现。李>
【问题讨论】:
-
您可以使用指令来设置订阅吗...指令可以使用 Host angular.io/api/core/Host 访问主机组件上的方法/值
-
您到底想要什么?如果你只是想重复使用相同的模板,你可以把它放在一个 html 文件中并从你的子组件中引用它
-
@David 不重用,可能是我走得太远了,但是当我们谈论继承时,我们的意思是扩展一些现有的功能,我们可以在 ts 文件中扩展组件,但是单独的 html子组件需要文件,我要问的是,如果该子 html 只是父组件 html 的扩展,但我仍然必须从父组件复制 html。但是,从下面的答案和 Rnd 来看,我觉得没有什么比 html 的继承更重要,而且视图应该以角度单独引用,但它使新开发人员的代码更难理解
-
@nobalG 你想让它像模板 html 一样,还是你也想将 appTitle 等属性移动到父组件并通过子组件传递值?
标签: angular inheritance publish-subscribe subscription