Erik Z
Erik Z

Reputation: 4770

Derive and subclass a directive so ContentChildren can find it?

I have a component HelloComponent. This component takes all content children which is of type MyButtonDirective and renders a button tag for each of them.

@Component({
  selector: 'hello',
  template: `
  <p>{{buttons.length}}</p>
  <button *ngFor="let b of buttons" (click)="b.onClick()">{{b.text}}</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @ContentChildren(MyButtonDirective, {descendants: true}) buttons: QueryList<MyButtonDirective>;
}


@Directive({
  selector: 'my-button'
})
export class MyButtonDirective  {
  @Input() text: string;
  @Output() click: EventEmitter<any> = new EventEmitter<any>();

  onClick() {
    console.log('my-button clicked');
    this.click.emit();
  }
}

Is there a way I can subclass or derive from MyButtonDirective to create a new directive och component that will be included in the contentchildren of the HelloComponent?

<hello>
  <my-button></my-button>
  <my-button></my-button>
  <extra-button></extra-button>   <-- How can this be included in contenchildren of Hello?
</hello>

I've made a Stackblitz for this.

Upvotes: 2

Views: 730

Answers (1)

j4rey
j4rey

Reputation: 2677

Just to simplify, I've created and AbstractButton

abstract class AbstractButton {
    text: string;
    abstract onClick();
}

The existing MyButtonDirective & ReplayButton now extends AbstractButton

@Directive({
    selector: 'my-button',
    providers: [{provide: AbstractButton, useExisting: forwardRef(() => MyButtonDirective)}]
})
export class MyButtonDirective extends AbstractButton {
    ...
}

The HelloComponent stays the same except the type in ContentChildren

...
export class HelloComponent  {
    @Input() name: string;
    @ContentChildren(AbstractButton, {descendants: true}) buttons: QueryList<AbstractButton>;
}

I also see you have ExtraButtonComponent which had the template <my-button>, but I am unsure if this would work, as its inside another component and is a child of that

Check out the StackBlitz Demo here.

Upvotes: 4

Related Questions