0

Всем привет и с наступающим Новым Годом.

Использую angular (последней версии) и angular material.

Есть 3 компонента:

  • header.component, в котором находится кнопка управления правым sidenav'ом
  • rigth-sidenav.component, в котором и находится тот самый sidenav
  • sidenav.component (это левое основное меню), в этом компоненте вызывается header.component, right-sidenav.component и контент

С Ангуляром впервые столкнулся, подскажите, пожалуйста, как открыть/закрыть sidenav из другого компонента (в моем случае кнопка находится в header.component).

Пробовал следующий вариант (но получал ошибку: TypeError: this.RightSidenavComponent.rightSidenav is undefined):

header.component.html

<button mat-button (click)="toggleRightSidenav()">Согласование до 16:00 сегодня</button>

header.component.ts

import { Component } from '@angular/core';
import { RightSidenavComponent } from '../right-sidenav/right-sidenav.component';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent {

	constructor(public RightSidenavComponent:RightSidenavComponent) {	}
	toggleRightSidenav() {
		this.RightSidenavComponent.rightSidenav.toggle();
	}
	
}

sidenav.component.html

<mat-sidenav-container class="sidenav-container">
	<mat-sidenav #sidenav mode="side" opened="true" class="sidenav"
				 [fixedInViewport]="true"> Sidenav	</mat-sidenav>
	<mat-sidenav-content>
		<app-header></app-header>
		<router-outlet></router-outlet>
		<app-right-sidenav #rSidenav></app-right-sidenav>
	</mat-sidenav-content>
</mat-sidenav-container>

sidenav.component.ts

import { Component, Directive, ViewChild } from '@angular/core';
import { RightSidenavComponent } from '../right-sidenav/right-sidenav.component';

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

export class SidenavComponent {
	
	@ViewChild('rSidenav') public rSidenav;
	constructor(public RightSidenavComponent: RightSidenavComponent) {
		this.RightSidenavComponent.rightSidenav = this.rSidenav;
	}
	
}

right-sidenav.component.html

<mat-sidenav #rightSidenav mode="side" opened="true" class="rightSidenav"
			 [fixedInViewport]="true" [fixedTopGap]="250">
	Sidenav
</mat-sidenav>

right-sidenav.component.ts

import { Component, Injectable } from '@angular/core';

@Component({
  selector: 'app-right-sidenav',
  templateUrl: './right-sidenav.component.html',
  styleUrls: ['./right-sidenav.component.scss']
})

@Injectable()
export class RightSidenavComponent {
	
	public rightSidenav: any;

	constructor() { }

}

1 ответ 1

0

SidenavService

import { Injectable } from '@angular/core';
import { MatSidenav } from '@angular/material';

@Injectable()
export class SidenavService {
    private sidenav: MatSidenav;


    public setSidenav(sidenav: MatSidenav) {
        this.sidenav = sidenav;
    }

    public open() {
        return this.sidenav.open();
    }


    public close() {
        return this.sidenav.close();
    }

    public toggle(): void {
    this.sidenav.toggle();
   }

Your Component

constructor(
private sidenav: SidenavService) { }

toggleRightSidenav() {
   this.sidenav.toggle();
}

App component.

@ViewChild('sidenav') public sidenav: MatSidenav;

constructor(private sidenavService: SidenavService) {
}

ngOnInit(): void {
  this.sidenavService.setSidenav(this.sidenav);
}

App Module

providers: [YourServices , SidenavService],

Работающий пример: https://stackblitz.com/edit/angular-tku8zp

Больше ответов и комментариев здесь: https://stackoverflow.com/questions/48073057/angular-open-close-sidenav-from-another-component (аналогичный мой вопрос)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.