Class inheritance support

后端 未结 2 1331
轻奢々
轻奢々 2020-11-30 00:55

I am building an Angular2 application in Typescript and would like to use the class system functionality (read: class inheritance) offered by Typescript. However, it seems t

相关标签:
2条回答
  • 2020-11-30 01:31

    You can use a local template variables with a ContentChildren query to create a list of all components with a shared base class. Here is a plunk for the code below. This approach was taken from the suggestion in Kara Erickson's Rookie mistakes blog post.

    In the template each child component is marked with #child:

      <app-container>
        <app-child1 #child></app-child1>
        <app-child1 #child></app-child1>
        <app-child1 #child></app-child1>
        <app-child1 #child></app-child1>
        <app-child2 #child></app-child2>
      </app-container>
    

    This can then be used to select all the components with the shared base component:

      import { Component, QueryList, ContentChildren, ViewChildren, AfterViewInit, AfterContentInit } from '@angular/core';
      import { BaseComponent } from '../base/base.component';
      import { Child1Component } from '../child1/child1.component';
      import { Child2Component } from '../child2/child2.component';
    
      @Component({
        selector: 'app-container',
        templateUrl: './src/container/container.component.html'
      })
      export class ContainerComponent implements AfterContentInit  {
        @ContentChildren('child') allChildren: QueryList<BaseComponent>;
        @ContentChildren(Child1Component) child1Chdilren: QueryList<Child1Component>;
        @ContentChildren(Child2Component) child2Chdilren: QueryList<Child2Component>;
    
        constructor() { }
    
        ngOnInit() {
        }
    
        ngAfterContentInit() {
        }
    
      }
    
    0 讨论(0)
  • 2020-11-30 01:51

    Add a provider to each derived component, aliasing the base component to the derived component:

    @Component({
      selector: 'child-comp2',
      template: '<div>child component #2</div>',
      providers: [{provide: BaseComponent, useExisting: forwardRef(() => ChildComponent2) }]
    })
    export class ChildComponent2 extends BaseComponent {
    }
    
    @Component({
      selector: 'child-comp1',
      template: '<div>child component #1</div>',
      providers: [{provide: BaseComponent, useExisting: forwardRef(() => ChildComponent1) }]
    })
    export class ChildComponent1 extends BaseComponent {
    }
    

    Plunker: http://plnkr.co/edit/5gb5E4curAE2EfH2lNZQ?p=preview

    0 讨论(0)
提交回复
热议问题