【问题标题】:Access nested content children访问嵌套内容子项
【发布时间】:2019-03-12 10:49:52
【问题描述】:
@Directive({
  selector: '[some-directive]'
})
export class SomeDirective...
@Component({
  selector: 'inner-component',
  template: `
    <div some-directive></div>
  `
})
export class InnerComponent {
}
@Component({
  template: `
    <inner-component></inner-component>
  `
})
export class OuterComponent {
  @ContentChildren(SomeDirective, {descendants: true}) elementsWithDirective: QueryList<SomeDirective>;
}

这是获取这些指令的正确方法吗? elementsWithDirective 返回空结果数组。我无法以这种方式访问​​它。我可以摆脱这个问题的唯一方法是将&lt;div app-some-directive&gt;&lt;/div&gt; 直接放在 OuterComponent 的视图中,但我想避免它。

【问题讨论】:

  • 什么时候访问 elementsWithDirective ?它应该在 ngAfterContentInit 期间设置
  • 无论我在哪里做,即使我在 10 秒后控制台 elementsWithDirective,结果数组仍然是空的。

标签: angular typescript


【解决方案1】:

AFAIK 目前无法直接从组件中获取孙子元素。 我不知道你的用例是什么,但你可以:

  1. @ViewChild(InnerComponent) innerComponent: InnerComponent 添加到您的外部组件
  2. @ViewChild(SomeDirective) someDirective: SomeDirective 添加到您的内部组件
  3. 从外部组件通过 ngAfterViewInit 中的内部组件访问您的指令 ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); }

stackblitz here

【讨论】:

    【解决方案2】:

    您似乎对 contentChildren 和 viewChildren 感到困惑。在您的情况下,您应该使用 viewChildren 在 InnerComponent 中查询 SomeDirective,并将结果发送到 OuterComponent,例如

    @Component({
      selector: 'outer-component',
      template: `    <inner-component 
        (elementsWithDirectiveChanges)="elementsWithDirectiveChanged($event)"> 
        </inner- 
        component>`
    })
    export class OuterComponent {
      elementsWithDirectiveChanged(change: any) {
        console.log(change);
      }
    }
    
    @Component({
      selector: 'inner-component',
      template: `
        <div some-directive>inner</div>
      `
    })
    export class InnerComponent {
      @ViewChildren(SomeDirective) elementsWithDirective!: QueryList<SomeDirective>;
      @Output() elementsWithDirectiveChanges = new EventEmitter();
    
      ngAfterViewInit() {
        this.elementsWithDirectiveChanges.emit(this.elementsWithDirective);
      }
    }
    

    演示https://stackblitz.com/edit/angular-2oesig?file=src%2Fapp%2Fhello.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2015-09-11
      • 2018-07-29
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多