Javascript Angular 5:为所有ContentChildren(甚至子组件中的子组件)获取查询列表

Javascript Angular 5:为所有ContentChildren(甚至子组件中的子组件)获取查询列表,javascript,html,angular,directive,Javascript,Html,Angular,Directive,我有以下html结构,其中foo和bar是两个指令,baz是一个自定义组件 <div foo> <div bar></div> <baz><baz> <baz><baz> </div> 。。。而foo-指令看起来是这样的: // ... @Directive({ selector: '[foo]' }) export class FooDirective implements Aft

我有以下html结构,其中
foo
bar
是两个指令,
baz
是一个自定义组件

<div foo>
  <div bar></div>
  <baz><baz>
  <baz><baz>
</div>
。。。而
foo
-指令看起来是这样的:

// ...
@Directive({
  selector: '[foo]'
})
export class FooDirective implements AfterContentInit {

  @ContentChildren(BarDirective)
  m_bars: QueryList<BarDirective>;

  public ngAfterContentInit(): void {

    console.log('barCount:', this.m_bars.length);
  }
}
根本没有任何效果。

检查此堆栈闪电战(注意控制台输出):

您必须通过输出将其链接起来。QueryList有一个可观察的更改,您可以尝试使用它作为输出。大致如下:

@ContentChildren() something: QueryList<Type>;

@Output() queryListChange = new EventEmitter();

ngOnInit() {
    this.something.changes.subscribe(v => {
        this.queryListChange.emit(v);
    }
}
@ContentChildren()某物:QueryList;
@Output()queryListChange=neweventemitter();
恩戈尼尼特(){
this.something.changes.subscribe(v=>{
this.queryListChange.emit(v);
}
}
在上面的组件中,您需要订阅此输出:

(queryListChange)=“onQueryListChange($event)”

在onQueryListChange中,您需要将收到的项目与组件自己的ViewChildren合并

如果需要更多层次的嵌套,则以相同的方式传递


<>太长了,读不下去了,我不知道如何合并查询列表,所以我只从他们那里得到了原始数组,并把它们合并到了我的StabLimz中。

< P>这是不可能的,这很糟糕。请看进一步的信息。我将引用TL;DR版本作为参考:

简言之:我们只查询组件自己的内容,而不是来自其他模板的内容。这是有意义的,因为模板形成了一个名称空间#foo在一个模板中可能意味着一件事,而在另一个模板中可能意味着完全不同的事。名称可能相同,但含义却完全不同


感谢您的输入。
foodirection
QueryList
不会更改。如果我将
this.m\u bars.changes.subscribe(i=>console.log(i.length));
放入
ngAfterContentInit()中
它不会输出任何东西。而且我不希望修改
baz
-组件源代码,只是为了让它的所有子组件(具有
-指令)冒泡以某种方式进入
m_条
。它确实会发生变化,只是没有按照您期望的顺序进行,而且您肯定必须修改baz组件源代码,因为您试图克服一个限制(如果您要求,这是一个合理的限制)无法从一件事进入另一件事的关注领域。如果我有时间,我会尝试为你做一次stackblitz。查看我的最新答案
@ContentChildren(BarDirective, { descendants: true })
m_bars: QueryList<BarDirective>;
@ContentChildren() something: QueryList<Type>;

@Output() queryListChange = new EventEmitter();

ngOnInit() {
    this.something.changes.subscribe(v => {
        this.queryListChange.emit(v);
    }
}