提问人:orangecheese 提问时间:7/4/2023 更新时间:7/8/2023 访问量:152
单击背景时关闭侧边导航
Close sidenav when backdrop is clicked
问:
我是 Angular Material、ngrx 和现代 Angular 的新手。尝试使用具有标题和菜单图标的工具栏以及用于保存链接的侧导航来实现基本标题布局。当我单击菜单图标时,侧边栏应该会打开,当我单击侧边栏(背景)之外的区域时,它应该会关闭。我使用 ngrx 示例应用程序作为参考。
我尝试在用户使用 (click) 和 (backdropClick) 单击侧导航容器时发出事件。
app.component.ts(app.component.ts)
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import * as fromRoot from '@client-app/reducers';
import { LayoutActions } from '@client-app/core/actions';
@Component({
selector: 'app-root',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<app-layout (closeMenu)="closeSidenav()">
<app-toolbar (openMenu)="openSidenav()">Memories</app-toolbar>
<app-sidenav [open]="(showSidenav$ | async)!">
</app-sidenav>
<router-outlet></router-outlet>
</app-layout>
`,
})
export class AppComponent {
showSidenav$: Observable<boolean>;
constructor(private store: Store) {
this.showSidenav$ = this.store.select(fromRoot.selectShowSidenav);
}
closeSidenav() {
this.store.dispatch(LayoutActions.closeSidenav());
}
openSidenav() {
this.store.dispatch(LayoutActions.openSidenav());
}
}
layout.component.ts(布局.组件.ts)
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-layout',
template: `
<mat-sidenav-container fullscreen>
<ng-content></ng-content>
</mat-sidenav-container>
`,
})
export class LayoutComponent {
@Output() closeMenu = new EventEmitter<void>();
}
sidenav.component.ts(英语:sidenav.component.ts)
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-sidenav',
template: `
<mat-sidenav
position="end"
[opened]="open"
>
<mat-nav-list>
<a mat-list-item href="login">Login</a>
<a mat-list-item href="signup">Signup</a>
</mat-nav-list>
</mat-sidenav>
`,
styles: [
`
mat-sidenav {
width: 200px;
}
`,
],
})
export class SidenavComponent {
@Input() open = false;
}
工具栏.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-toolbar',
template: `
<mat-toolbar color="primary">
<ng-content></ng-content>
<button mat-icon-button (click)="openMenu.emit()" aria-label="menu">
<mat-icon>menu</mat-icon>
</button>
</mat-toolbar>
`,
styles: [
`
mat-toolbar {
display: flex;
justify-content: space-between;
}
`,
],
})
export class ToolbarComponent {
@Output() openMenu = new EventEmitter<void>();
}
答:
0赞
timdeschryver
7/8/2023
#1
closeMenu
within 从不发出值,因此永远不会调度操作,并且侧边栏不会关闭。LayoutComponent
NgRx 示例应用关闭组件中的菜单。SidenavComponent
@Component({
selector: 'bc-sidenav',
template: `
<mat-sidenav
#sidenav
[opened]="open"4
👇👇👇👇
(keydown.escape)="sidenav.close()"
👇👇👇👇
(closedStart)="closeMenu.emit()"
disableClose
>
<mat-nav-list>
<ng-content></ng-content>
</mat-nav-list>
</mat-sidenav>
`,
styles: [
`
mat-sidenav {
width: 300px;
}
`,
],
})
export class SidenavComponent {
@Input() open = false;
@Output() closeMenu = new EventEmitter<void>();
}
评论