Angular 2 | cannot get child directives with @ContentChildren

I am trying to get nested directives from the parent directive, but @ContentChildren is not populated. basically I create a lazy load on the images, each image is a nested directive from the parent directive


Example:

parent.directive.ts

import ...

@Directive({
    'selector': 'parentSelector'
})
export class ParentDirective implements onInit, AfterContentInit {
    @ContentChildren(ChildDirective) private items: QueryList<ChildDirective>;

    ngOnInit(): void {}

    ngAfterContentInit(): void {
        console.log(this.items, this.items.toArray()); // <---

        // call a child directive method...
        this.items.forEach((item: ChildDirective) => {
            item.makeSomething();
        });
    }
}

was this.itemsnot filled here

child.directive.ts

import ...

@Directive({
    selector: 'childSelector'
})
export class ChildDirective {
    makeSomething(): void {
        console.log('called from ParentDirective');
    }
}

app.component.ts

import ...

@Component({
    selector: 'app',
    template: `<div>
        <some-component parentSelector [items]="itemsData"></some-component>
    </div>`
})
export class AppComponent {
    // NOTE: "itemsData" is loaded asynchronously from a service
    ...
}

the "itemsData" property is loaded asynchronously from the service

some-component.component.html

<!-- 'items' was obtained from AppComponent @Input('items')
     see also: 'itemsData' on AppComponent
-->

<div *ngFor="let image of images">
    <img childSelector src="image.src">
</div>
Problem

linked to the "some components" loop, since data is loaded asynchronously, @ContentChildren is empty.

NOTE: all images are displayed on some component

any ideas? thanks in advance.

+4
1

( ​​ 2.0.1), @ContentChildren() .

@ContentChildren(ChildDirective, {descendants: true})

2.0.1 true .

+1

Source: https://habr.com/ru/post/1656998/


All Articles