簡體   English   中英

訪問嵌套內容的子級

[英]Access nested content children

@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返回空結果數組。 我無法以這種方式訪問​​它。 我唯一可以解決此問題的方法是將<div app-some-directive></div>直接放在OuterComponent的視圖內,但我想避免這種情況。

似乎您對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

AFAIK當前無法直接從組件中獲取孫元素。 我不知道您的用例是什么,但是您可以:

  1. @ViewChild(InnerComponent) innerComponent: InnerComponent到外部組件
  2. @ViewChild(SomeDirective) someDirective: SomeDirective到內部組件
  3. 從外部組件通過ngAfterViewInit ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); }內部組件訪問您的指令ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); } ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); }

這里的閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM