Есть ли какие-либо способы получить ElementRef и Component ref в ViewChildren? - PullRequest
1 голос
/ 18 октября 2019

Я хочу получить список родных элементов и связанных с ними компонентов из вида.

Я постараюсь сделать что-то подобное, но это не работает:

@ViewChildren('element', { read: [ElementRef, MyComponent] }) private elements: QueryList<any>; // <-- not work

or

@ViewChildren('element', { read: MyComponent }) private elements: QueryList<MyComponent>;
...
this.elements.first.nativeElement // <-- undefined

Это работает, но выглядит не так:

@ViewChildren('element', { read: ElementRef }) private elements: QueryList<ElementRef>;
@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;

мой короткий пример шаблона:

<virtual-scroller #scroll>
  <my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>

Ответы [ 3 ]

2 голосов
/ 18 октября 2019

Один из способов решить эту проблему - внедрить в каждый компонент ElementRef в качестве открытого свойства, а затем перебрать компоненты (полученные из ViewChildren), вы можете получить доступ ко всему, что хотите.

my-component.component.ts

@Component({ /* ... */ })
export class MyComponent {
 /* ... */

 constructor (public elementRef: ElementRef) { }

 /* ... */
}

parent.component.html

<virtual-scroller #scroll>
  <my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>

parent.component.ts

@ViewChildren('element', { read: MyComponent }) private components: QueryList<MyComponent>

/* ... */

ngAfterViewChecked () {
 this.components.forEach(c => console.log(c.elementRef))
}
2 голосов
/ 18 октября 2019

Один из способов сделать это - вставить:

@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;

в родительский компонент и выставить elementRef от дочернего:

class MyComponent {
    constructor(public elementRef: ElementRef) {}
}

, а затем просто получить доступ к elementRef напрямую:

this.components.forEach(component => component.elementRef);
0 голосов
/ 18 октября 2019

Вы можете использовать ContentChildren вместо ViewChildren

@ContentChildren(YourComponent) components: QueryList<YourComponent>;

Я сделал пример в stackblitz

https://stackblitz.com/edit/angular-tfjh6e

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...