Angular ContentChildren extended class

I have 3 components. 1 parent component that can wrap one of the two child components inside ng content. My child components have common functionality, so they extend an abstract class that has common functionality.

When I try to use ContentChildren to get a reference to ng-content, it works fine if I use one of the child classes. When I refer to the abstract class it doesn't work. Is there a way to make this work? plkr: http://plnkr.co/edit/f3vc2t2gjtOrusfeesHa?p=preview

Here is my code:

Child abstract class:

    abstract export class Child{
      value: any;
      abstract setValue();
    }    

      

My parent code:

@Component({
  selector: 'parent',
  template: `
    <div>
      parent
      <ng-content></ng-content>
    </div>
  `,
})
export class Parent {
  @ContentChild(Child) 
  child: Child;
  name:string;
  constructor() {

  }
   ngAfterViewInit() {
     this.child.setValue();
   }
}

      

First child:

@Component({
  selector: 'child1',
  template: `
    <div>
       value is: {{value}}
    </div>
  `,
})
export class Child1 extends Child {
  name:string;
  constructor() {

  }
   setValue() {this.value = 'Value from child 1'}
}

      

Second child:

@Component({
  selector: 'child2',
  template: `
    <div>
      value is: {{value}}
    </div>
  `,
})
export class Child2  extends Child {
  name:string;
  constructor() {

  }
  setValue() {this.value = 'Value from child 2'}
}

      

+3


source to share


1 answer


I solved it using:

into my component decorator for Child1

providers: [{provide: Child, useExisting: forwardRef(() => Child1)}],

      

into my component decorator for Child2



providers: [{provide: Child, useExisting: forwardRef(() => Child2)}],

      

You can now see the new io example from angular:

https://angular.io/guide/dynamic-component-loader

+6


source







All Articles