angular - Angular 6 创建一个基础组件并在 html 中调用它的父组件?
问题描述
我想要达到的目标
我有一个正在为练习而构建的 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 中,这种共享功能的实现方式不同。
我建议你看看角度嵌入。在您的示例中,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>
in将PageBaseComponent
被您在<app-page-base></app-page-base>
标签之间放置的内容替换。
通过这种方式,您可以在其中创建所需的任何基本布局,PageBaseComponent
并在所有页面中共享它。
这里的逻辑保持解耦。这可能是好事也可能是坏事,这取决于你想要什么。
为了为多个组件创建一些基本共享逻辑,您需要创建一个简单的类 - 没有@Component装饰器。然后用你的组件扩展它。请注意,组件使用 Angular 依赖注入系统。因此,当您将一些变量写入组件的构造函数时,Angular 会尝试使用其 DI 系统来解析它。在您的示例中,它会失败。
所以,总结一下——如果你想创建共享模板,请使用嵌入。如果您想创建共享行为 - 使用基类(没有组件装饰器)。
推荐阅读
- macos - Mac OS X:如何在 emacs 客户端的 shell 中永久更改提示符(PS1 的值)?
- android-studio - 检查失败:Thread::Current() != GetDebugThread() (Thread::Current()=0x7f7f241e00, GetDebugThread()=0x7f7f241e00) 预期事件线程
- outlook - 在 EWS 中创建不属于对话的新电子邮件
- python-3.x - 为什么我们在 python 参考中使用空括号从头开始书籍数据科学?
- python - 与docker内部python后端的节点通信中的角度失败
- python - Python NET 初始化一个锯齿状数组
- eclipse - Linux 上的 Eclipse Oxygen 重启后未启动
- ios - 如何在毫秒的视频中获取帧
- android - Android 构建在 Mac 机器中失败
- swift - 在主线程中调用方法会影响其子方法