代码之家  ›  专栏  ›  技术社区  ›  Ben Beri

Angular6创建一个基本组件并用HTML调用它的父组件?

  •  2
  • Ben Beri  · 技术社区  · 7 年前

    我想达到的目标

    我有一个客户关系管理小组正在为实践而建立。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
    

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Daniil Andreyevich Baunov    7 年前

    创建基本组件的想法 PageBaseComponent 相当不错。然而,在角度上,这种共享功能是以不同的方式实现的。

    我建议你看一下角度超越。在您的示例中, 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 并在所有页面上共享。

    这里的逻辑保持分离。这可能是好事,也可能是坏事,这取决于你想要什么。

    为了为多个组件创建一些基本共享逻辑,您需要创建一个简单的类-没有 @组件 装饰者。然后用组件扩展它。 注意,组件与角依赖注入系统一起工作。因此,当您将一些变量写入组件的构造函数时,Angular会尝试用它的DI系统来解析它。在您的示例中,它将失败。

    所以,总结一下——如果您想创建共享模板,那么就使用超越。 如果要创建共享行为,请使用基类(不带组件修饰器)。

    推荐文章