Доступ к дочернему элементу ViewChildren Querylist (Angular) - PullRequest
3 голосов
/ 18 апреля 2019

Я пытаюсь получить доступ к n-му дочернему списку вопросов для детей.

Ниже мой TS:

@ViewChildren(PopoverDirective) popovers: QueryList<PopoverDirective>;
console.log(this.popovers)

console.log показывает изменения, first, last, length и _results.

Как я могу получить доступ к n-му ребенку (т.е. 3-му, а не первому)?

Когда я пытаюсь сделать это с помощью _results (то есть this.popovers._results [2]), я получаю сообщение об ошибке.

Спасибо.

Ответы [ 2 ]

4 голосов
/ 18 апреля 2019

На самом деле есть пара методов, к которым вы можете обратиться к конкретному внутри вас QueryLists

1-й метод: .filter ()

Вы также можете использовать .map и .reduce в зависимости от ваших предпочтений

// Since if you have 3 items in an array, the counting starts at 0, so 1 is the 2nd element
const elementTwo = this.popovers.filter((element, index) => index === 1);


// Or if you want to be specific based on the data inside the PopoverDirective
// and if that PopoverDirective has an @Input() name, you can access it by:
const elementTwo = this.popovers.filter((element, index) => element.name === 'John');

2-й метод: .forEach ()

// You can perform any action inside the .forEach() which you can readily access the element
this.popovers.forEach((element, index) => console.log(element));

3-й метод: первый и последний

this.popovers.first         // This will give you the first element of the Popovers QueryList

this.popovers.last          // This will give the last element of the Popovers QueryList

Список необработанных массивов: .toArray ()

this.popovers.toArray();    // This will give you the list of popovers caught by your QueryList
1 голос
/ 18 апреля 2019

вы можете использовать метод toArray (), а затем вы можете получить доступ по индексу.

...