我正在尝试动态创建一个远程JSON的sidenav,它运行正常,它从URL获取JSON并将其解析为导航列表。现在我想在console.log中选择导航列表项,我无法做到,我在线查找了几个解决方案,但没有用。这是我的代码:
服务:
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
interface Applications {
AUTO_ID: number;
REGISTARSKI_BROJ: string;
AUTO_TIP: string;
GODINA_PROIZVODNJE: string;
TIP_MOTORA: string;
BROJ_SASIJE: string;
SNAGA_HP: number;
KUPAC_ID: number;
}
@Injectable()
export class MenuService {
objectKeys = Object.keys;
private url = `MY_URL`;
public apps: Applications[];
constructor(public router: Router, protected http: HttpClient) { }
menu(e) {
e.preventDefault();
this.http.get(this.url).subscribe(result => {
this.apps = result as Applications[];
}, error => console.error(error));
}
ispisi(e) {
e.preventDefault();
console.log(this.apps); // WHEN I DO IT LIKE THIS, IT LOGS ALL OF THE OBJECTS TO THE CONSOLE
this.router.navigate(['table']);
}
}
HTML模板:
<mat-sidenav-container>
<mat-sidenav #sidenav mode="push">
<mat-toolbar>
Glavni meni
</mat-toolbar>
<mat-nav-list>
<mat-list-item (click)="sidenav.toggle()" [routerLink]="['/']"><i class="material-icons">assessment</i>Dashboard</mat-list-item>
<mat-accordion>
<mat-expansion-panel (click)="menuService.menu($event)">
<mat-expansion-panel-header>
<mat-panel-title>
<i class="material-icons">directions_car</i>Automobili
</mat-panel-title>
</mat-expansion-panel-header>
<mat-nav-list *ngIf="menuService.apps">
<mat-list-item (click)="menuService.ispisi($event)" *ngFor="let app of menuService.apps">
{{app.REGISTARSKI_BROJ}}
</mat-list-item>
</mat-nav-list>
</mat-expansion-panel>
</mat-accordion>
</mat-nav-list>
</mat-sidenav>
<mat-toolbar color="primary">
<button mat-icon-button (click)="sidenav.toggle()">
<mat-icon>menu</mat-icon>
</button> Service stats
<span class="example-spacer"></span>
<button (click)="authService.logOut()" matTooltip="Izloguj se" matTooltipPosition="below" class="user" mat-icon-button>
<i class="material-icons">account_circle</i>
</button>
</mat-toolbar>
</mat-sidenav-container>
答案 0 :(得分:0)
我不确定我会得到你想做的事,但如果你想要选择的菜单,你应该改变
<mat-list-item (click)="menuService.ispisi($event)" *ngFor="let app of menuService.apps">
{{app.REGISTARSKI_BROJ}}
</mat-list-item>
这样的事情
<mat-list-item (click)="menuService.ispisi(app)" *ngFor="let app of menuService.apps">
{{app.REGISTARSKI_BROJ}}
</mat-list-item>
通过这种方式,您可以访问所选菜单,并可以从中实现所选逻辑