17

I have 3 components. 1 parent component that can wrap one of any 2 child components inside an ng-content. My child components have shared functionality so they are extending an abstract class that have the shared functionality.

When I try to use ContentChildren to get the ng-content reference, it works fine if I am using one of the child classes. When I reference the abstract class, it does not work. Is there a way to make this work? plkr is: 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'}
}
Mohy Eldeen
  • 1,261
  • 2
  • 13
  • 24
  • Possible duplicate of [Class inheritance support](https://stackoverflow.com/questions/36063627/class-inheritance-support) – Juan Apr 25 '19 at 12:43
  • So I delete it? Not sure if its really a duplicate, but not sure whats the ask as well! – Mohy Eldeen Apr 26 '19 at 17:56
  • Uhm, I'm not sure. Flagging a post as possible duplicate automatically adds the comment. Posts that are duplicate usually have a notice at the top linking to the other solution, like this one: https://stackoverflow.com/questions/55684960/why-does-python-start-at-index-1-as-opposed-to-0-when-indexing-a-list-from-th. – Juan Apr 26 '19 at 21:42
  • 1
    NP, I will review both at some point and then approve it as duplicate if I though it is. Thanks for explanation. – Mohy Eldeen Apr 26 '19 at 21:49

1 Answers1

38

I solved this by 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 look at the new io example from angular:

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

Mohy Eldeen
  • 1,261
  • 2
  • 13
  • 24