Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ContentChildren of extended class

Tags:

angular

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'}
}
like image 666
Mohy Eldeen Avatar asked May 11 '17 23:05

Mohy Eldeen


1 Answers

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

like image 117
Mohy Eldeen Avatar answered Nov 08 '22 19:11

Mohy Eldeen