Angular 16 ViewChild components in NgbOffcanvas is returning undefined

Discussão em 'Angular' iniciado por Jim Garrido, Novembro 17, 2024.

  1. Jim Garrido

    Jim Garrido Guest

    I have an offcanvas and a x-component in it and whenever I try to use ViewChild to get the x-component, it always returns undefined.

    Error (https://i.sstatic.net/Lh6DUTZd.png)

    Code

    import { Component, inject, TemplateRef, ViewChild } from '@angular/core';
    import { LazyloadedComponent } from '../lazyloaded/lazyloaded.component';
    import { NgbOffcanvas } from '@ng-bootstrap/ng-bootstrap';

    @Component({
    selector: 'app-offcanvas',
    templateUrl: './offcanvas.component.html',
    styleUrls: ['./offcanvas.component.scss']
    })
    export class OffcanvasComponent {

    @ViewChild('offcanvas') offcanvas: TemplateRef<OffcanvasComponent>;
    @ViewChild('lazy') lazy: LazyloadedComponent;
    private offcanvasService = inject(NgbOffcanvas);

    open() {
    this.offcanvasService.open(this.offcanvas);
    }

    test() {
    this.lazy.test();
    }
    }


    <ng-template #offcanvas let-offcanvas>
    <div class="offcanvas-body">
    <app-lazyloaded #lazy></app-lazyloaded>
    <button (click)="test()">TEST</button>
    </div>
    </ng-template>


    When I replicate the issue on Angular 18, it doesn't happen anymore.

    Repo for reference: https://github.com/jim-dev12/angular-16-ngb-viewchild-issue

    Tried using @ViewChild to access the component properties. I expected it to access the property normally but it is returning undefined.

    Continue reading...

Compartilhe esta Página