gpt4 book ai didi

javascript - 基于路线显示元素 - Angular

转载 作者:行者123 更新时间:2023-12-01 01:51:57 25 4
gpt4 key购买 nike

我在尝试设置导航栏时遇到了很大的麻烦 display:none根据我想要的路线。我确实成功订阅了该路线,但我无法根据它关联它的显示。

到目前为止我有这个:

export class AppComponent implements OnInit {

jwtHelper: JwtHelper = new JwtHelper();
public location = '';

constructor(private authService: AuthService, private router: Router, private http: Http) {
this.location = router.url;
this.router.events.subscribe((location) => {
console.log(location);
return true;
});
}
}

对于我的应用程序组件.ts

<div class="app-nav">
<!-- style="display:none; -->
<app-navbar></app-navbar>
</div>
<div class="container outlet">

<router-outlet></router-outlet>

</div>

和 html

<app-nav></app-nav>仅当 URL 为空时,选择器不得出现,即 '/'路线,但必须在所有其他 route 可用。有人可以帮助我吗?

最佳答案

所以你基本上可以在这里利用 rxjs 的力量。this.router.events 是一个事件流(称为 Observable)。我们可以获取流并将其(map)转换为 bool 属性。然后我们在要切换的组件上设置一个 *ngIf ,如下所示:

<app-nav *ngIf="showNav$ | async"></app-nav>

由于 this.router.events 是一个流,因此每次发出新值时,都会生成一个新的 bool 值。 html 模板中使用的流与 async 管道一起使用,将 bool 值解包到 html 中,它还会自动为您订阅和取消订阅。

完整的工作 stackblitz 是 here .

PS。顺便说一句,不要因为有人对你的问题投反对票而灰心丧气,这种情况在这里发生得越来越频繁,而且没有解释原因。 我回复了你的问题,因为它很有道理,而且答案对其他人也有帮助。

关于javascript - 基于路线显示元素 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51410719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com