我想要实现的目标
我有一个 CRM 面板,我正在为练习而构建。该 CRM 面板有页面,屏幕左侧有导航。
每个页面都应该显示标题。
这意味着我必须包括 <h2>title</h2>
在每个组件模板中。
我想到的解决方案
如果我创建一个组件会怎样 PageBaseComponent
得到title
:
@Component({
selector: 'app-page-base',
templateUrl: './page-base.component.html',
styleUrls: ['./page-base.component.scss']
})
export class PageBaseComponent implements OnInit {
constructor(private title: string) { }
ngOnInit() {
}
}
然后每当我有一个新页面时继承它:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent extends PageBaseComponent implements OnInit {
constructor() {
super("Dashboard");
}
ngOnInit() {
}
}
并且在PageBase
的模板中我愿意
<h1>{{title}}</h1>
如果可能的话,在我继承它的组件中我可以做这样的事情:
<parent-component-html></parent-component-html>
my page info here blab blabla
可以吗?实现该结构的正确方法是什么?
最佳答案
您创建基础组件的想法 PageBaseComponent
很不错。但是,在 Angular 中,这种共享功能的实现方式不同。
我建议您看一下 Angular 位移。在您的示例中 PageBaseComponent
它没有太多的功能。要点 - 是共享模板。
因此,在这种情况下,您可以创建一个 PageBaseComponent
组件的方式如下:
@Component({
selector: 'app-page-base',
templateUrl: './page-base.component.html',
styleUrls: ['./page-base.component.scss']
})
export class PageBaseComponent implements OnInit {
@Input() title: string;
constructor() { }
ngOnInit() {
}
}
<h1>{{title}}</h1>
<ng-content></ng-content>
然后在您想要在模板中使用相同基本行为的所有页面中编写以下内容:
<app-page-base [title]="'Some Title'">
<!-- Current Page Content -->
</app-page-base>
<ng-content></ng-content>
在PageBaseComponent
将替换为您在 <app-page-base></app-page-base>
之间输入的内容标签。
通过这种方式,您可以在 PageBaseComponent
中创建任何您想要的基本布局。并在所有页面上共享它。
这里的逻辑保持分离。这可能是好事也可能是坏事,具体取决于您想要什么。
为了为多个组件创建一些基本的共享逻辑,您可能想要创建一个简单的类 - 没有 @Component 装饰器。然后用你的组件扩展它。 请注意,组件与 Angular 依赖注入(inject)系统一起工作。因此,当您将一些变量写入组件的构造函数时,Angular 会尝试使用其 DI 系统来解析它。在您的示例中,它将失败。
因此,总结一下 - 如果您想创建共享模板,请使用嵌入。 如果您想创建共享行为 - 使用基类(没有组件装饰器)。
关于Angular 6 创建一个基本组件并在 html 中调用它的父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365824/