【发布时间】:2021-11-08 16:14:18
【问题描述】:
提示:我对 Angular 很陌生。我希望这个问题能得到解答,因为它是我可以用我目前在 Angular 中的知识/词汇对我的问题给出的最详细的解释。
我有以下设置:
我的App组件定义了一个PageNavigation数组,并在构造函数中填充:
页面导航界面
import {Route} from "@angular/router";
export interface PageNavigation {
displayName : string;
route : Route;
}
应用组件
import {Component} from '@angular/core';
import {Router} from "@angular/router";
import {PageNavigation} from "src/app/navigation/page-navigation";
import {TemplatesComponent} from "src/app/pages/templates/templates.component";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
pageNavigations: PageNavigation[];
constructor(public router: Router) {
this.pageNavigations = [
{displayName: "Templates", route: {path: "templates", component: TemplatesComponent}}
]
this.pageNavigations.forEach(pageNavigation => { //<-- I use the Array for Routing but that's probably not interesting for my problem
this.router.config.push(pageNavigation.route);
});
}
}
然后我想在我的应用组件中创建一个侧边栏,并交出数组
侧边栏组件
import {Component, Input, OnInit} from '@angular/core';
import {PageNavigation} from "src/app/navigation/page-navigation";
import {Router} from "@angular/router";
@Component({
selector: 'tara-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.less']
})
export class SidebarComponent {
public selectedRoute?: any;
constructor(public router : Router) { }
@Input('pageNavigations') pageNavigations : PageNavigation[] | any;
navigate(): void {
alert(this.selectedRoute);
// this.router.navigate([this.selectedRoute]).then(function () {
// // success
// }, function () {
// // error
// });
}
}
对应的html:
app.component.html
<tara-sidebar [pageNavigations]="pageNavigations"></tara-sidebar>
<router-outlet></router-outlet>
在 app.component.html 中,我只是将值“交给”
sidebar.component.html
<p-listbox [options]="pageNavigations" [(ngModel)]="selectedRoute" optionLabel="displayName" optionValue="route" (ngModelChange)="navigate()" ></p-listbox>
在 SideBar 中,我创建了一个 prime-ng 列表框。它显示正确的标签(在我的例子中是“模板”)。然而,点击它,触发 navigate() 方法,我收到一个带有“null”或“[object] [object]”的警报(它在两者之间交替,意味着第一次单击 = null,第二个 = [object] [对象],第三个 = null,...
如果可能的话,你能解释一下发生了什么吗,因为我希望要么总是得到空值(在导航()之后输入蜂鸣“触发”),要么代码只是在工作并给我我的数据已点击。
第一次点击模板
第二次点击模板 我已经尝试将 selectedRoute 的变量类型从 any 更改为 PageNavigation,但没有成功,它只是在警报中给我 undefined。
【问题讨论】:
标签: javascript html angular typescript input