viewChild виден только из компонента, у которого есть переменная ссылки на шаблон. (и должен быть прочитан: ElementRef, а не прочитан: ViewContainerRef
, если у вашего компонента есть родительский элемент, от этого родительского элемента вам требуется доступ к компоненту, а затем доступ к ViewChildren. И да, вы получаете доступ к дочерним элементам, используяViewChild от родителя (или со ссылкой на шаблон)
например, наши дети
@Component({
selector: 'hello',
template: `<h1 #filterContainer>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
@ViewChild('filterContainer',{static:false}) filterComponent
}
Наши родители
<hello #hello name="{{ name }}"></hello>
<button (click)="log(hello.filterComponent)">button</button>
<button (click)="log2()">button</button>
export class AppComponent {
name = 'Angular';
@ViewChild(HelloComponent,{static:false}) hello
//or
//@ViewChild('hello',{static:false,read:HelloComponent}) hello
log(element)
{
console.log(element.nativeElement.innerHTML)
}
log2()
{
console.log(this.hello.filterComponent)
}
}
stackblitz