A
A
Artem2018-06-08 13:02:04
Angular
Artem, 2018-06-08 13:02:04

How to get child elements created by ngFor?

<select [(ngModel)]="selectedId" appSelect>
  <option #option *ngFor="let item of Items" [ngValue]="item.id ">{{item.name}}</option>
</select>

@ContentChildren('option') options: QueryList<ElementRef>;
...
ngContentViewInit() {
  this.options.changes.subscribe(...);
}

Is it possible to do the same but without #option template variable

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Eremin, 2018-06-08
@EreminD

how do you use ViewChildren?
Show me please

A
Arthur, 2018-06-09
@antoart

Artem , there is another option. It is similar, but it can be found in various creators of a bunch of all sorts of components for angular.

<div class="table-body">
    <ul class="table-list"
        directiveList>
      <li *ngFor="let item of items; let i = index; trackBy: trackByFn"
           class="table-item" directiveItem>
          {{item}}
      </li>
    </ul>
  </div>

There is a directiveList, there is a directiveItem.
The directiveList class contains a list of these "child" elements.
@Directive({
  selector: '[directiveList]',
  exportAs: 'directiveList'
})
export class DirectiveList {
/**
   * Children directives which placed on items
   */
  @ContentChildren(DirectiveItem, {read: ElementRef}) // получаем сразу как список ссылок на компоненты класса
  private _items: QueryList<DirectiveItem>;
}

ngAfterContentInit() {
    this._items.changes.subscribe(() => {
      this.coolFunc();
    });

}

What's the Difference?
You get rid of work with elements in a component. Because today you want to do something with the list of elements, but tomorrow you don’t want to, for this you just remove the directives. The component will not change much.
But anyway via @ContentChildren.
p.s. I totally forgot. Here is the empty directive itself
@Directive({
  selector: '[directiveItem]'
})
export class ClassNewInViewItemDirective {

  constructor() { }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question