首页 > 解决方案 > 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

有可能吗?实现该结构的正确方法是什么?

标签: angular

解决方案


您创建基础组件的想法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 系统来解析它。在您的示例中,它会失败。

所以,总结一下——如果你想创建共享模板,请使用嵌入。如果您想创建共享行为 - 使用基类(没有组件装饰器)。


推荐阅读