【问题标题】:Derive and subclass a directive so ContentChildren can find it?派生和子类化指令以便 ContentChildren 可以找到它?
【发布时间】:2020-09-04 07:45:33
【问题描述】:

我有一个组件 HelloComponent。该组件采用 MyButtonDirective 类型的所有内容子项,并为每个子项呈现一个按钮标记。

@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();
  }
}

有没有一种方法可以子类化或从 MyButtonDirective 派生来创建一个新的指令 och 组件,该组件将包含在 HelloComponent 的 contentchildren 中?

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

我为此创建了一个Stackblitz

【问题讨论】:

    标签: angular


    【解决方案1】:

    为了简化,我创建了 AbstractButton

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

    现有的MyButtonDirectiveReplayButton 现在扩展了AbstractButton

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

    HelloComponent 保持不变,除了 ContentChildren 中的类型

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

    我还看到您有 ExtraButtonComponent,它具有模板 &lt;my-button&gt;,但我不确定这是否可行,因为它位于另一个组件中并且是该组件的子组件

    查看StackBlitz Demo here

    【讨论】:

    • 这个,效果很好。谢谢。我一直在寻找这个。 :) 关于 ExtraButtonComponent 我读到 ContentChildren 在 ng-content 障碍之间不起作用。这可能是它在这里不起作用的原因吗?
    • 经过大量挖掘,我找到了这个链接(用于书签),这正是您试图通过extra-button 实现的目标。不幸的是,这样的功能不起作用。如果您使用内容项目在extra-button 中投影my-button,那将起作用。(查看Eliseo 的答案)stackoverflow.com/questions/52653376/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2013-08-20
    • 2011-08-15
    相关资源
    最近更新 更多