1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How to use @ViewChild with signals and effect() in Angular?

Discussão em 'Angular' iniciado por Kate Vel, Junho 5, 2025.

  1. Kate Vel

    Kate Vel Guest

    I'm using Angular 17+ with signals, and I ran into a problem when trying to control a <mat-sidenav> via a shared service and @ViewChild.

    I created a SidenavService that exposes a signal, which is updated from different components. My goal is to reactively open/close the MatSidenav from the signal.

    The problem: I can't use @ViewChild inside the constructor (where effect() needs to run), and it's not available until ngAfterViewInit(). But I also can't put the effect() inside ngAfterViewInit(). Is there a clean way to solve this pattern using signals and @ViewChild? Here's my setup:

    service.ts

    @Injectable({
    providedIn: 'root',
    })
    export class SidenavService {
    isOpen = signal(false);

    drawerState = this.isOpen.asReadonly();

    toggle() {
    this.isOpen.update((state) => !state);
    }

    open() {
    this.isOpen.set(true);
    }

    close() {
    this.isOpen.set(false);
    }
    }


    component.ts

    export class AppComponent implements AfterViewInit {
    @ViewChild('drawer') drawer!: MatSidenav;

    onDrawerToggle() {
    this.drawer.toggle();
    }

    constructor(private sidenavService: SidenavService) {
    const effectRef = effect(() => {
    if (this.drawer) {
    this.sidenavService.drawerState()
    ? this.drawer.open()
    : this.drawer.close();
    }
    });
    }

    ngAfterViewInit(): void {}
    }

    Continue reading...

Compartilhe esta Página