indexOf() 在 Angular2 中的 *ngIf 语句内创建"cannot read property"错误



我有一个在网站的不同区域调用的组件,其中嵌套了更多的组件,我希望根据路线显示这些组件。我想出了这个解决方案。

import { Component }                        from '@angular/core';
var routeLocation = window.location.pathname;
@Component({
selector: 'asset-packs',
template: `<h1>Asset Packs</h1>
<asset-expand *ngIf="routeLocation.indexOf('expand') > 0"></asset-expand>
<asset-newbus *ngIf="routeLocation.indexOf('rebrand') > 0"></asset-newbus>
`
})
export class PointAssetsComponent {
}

我的意图是使用

var routeLocation=window.location.pathname;

从浏览器中提取url并将其保存到一个变量中,然后我可以在*ngIf语句中调用该变量作为

*ngIf="routeLocation.indexOf('expand')>0">

正如你从引用的变量中看到的那样,我尝试了几种不同的方法来访问URL,并将我想要查找的确切文本与存储在其中的文本进行交换。无论哪种方式,我都会得到未定义的错误。

到目前为止,我还没有找到任何的例子

.indexOf()

专门用于ngular2,但从我所看到的情况来看,我使用了正确的语法。我最初试图使用

.contains()

,并得到了相同的错误。当我删除ngIf语句时,两个组件都显示得很好。当我把它们加进去的时候,这个问题就开始出现了。

我遇到过其他一些关于这个问题的文章,他们说这是Node中的AngularFire和FireBird模块引起的错误。我检查了一下,但这两个都不在我的应用程序中。

我唯一想的是,它必须是与语法有关的东西,否则我不会导入导致的东西

window.location.etc

零件工作。有人知道是什么原因造成的以及如何解决吗?

您可以在ts文件中执行此操作:

import { Router } from '@angular/router';
export class PointAssetsComponent {
public navExpand:boolean = false;
public navRebrand:boolean = false;
constructor(private router: Router) {
}
if (this.router.url.substring(0,7) === '/expand'){
this.navExpand = true;
} else if (this.router.url.substring(0,8) === '/rebrand'){
this.navRebrand = true;
}

HTML

@Component({
selector: 'asset-packs',
template: `<h1>Asset Packs</h1>
<asset-expand *ngIf="navExpand"></asset-expand>
<asset-newbus *ngIf="navRebrand"></asset-newbus>
`
})

相关内容

最新更新