angular - 单页应用程序Angular 6中的组件路由
问题描述
我正在使用 Angular 6,我的项目中有 4 个组件。我想在一个页面中添加所有这些组件,并且我希望正确的菜单项处于活动状态,并且当我滚动到单个页面中的不同组件时,url 会更改为正确的路由。我一直在努力解决这个问题,非常感谢任何帮助。
这是我的 header.component.html
<section class="module-small navbar-light">
<mdb-navbar SideClass="navbar fixed-top navbar-custom navbar-expand-lg scrolling-navbar ie-nav" [containerInside]="false">
<logo class="logo">
<img src="./assets/images/phf-logo.png" />
</logo>
<links class="links">
<ul class="navbar-nav mr-auto">
</ul>
<ul class="navbar-nav navbar-flex-icons">
<li class="nav-item active waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='about'}" routerLink="/about"
(click)="scroll(about,'about')">
<a class="nav-link">ABOUT<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='features'}" routerLink="/features" (click)="scroll(features,'features')">
<a class="nav-link">FEATURES</a>
</li>
<li class="nav-item waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='management'}" routerLink="/management" (click)="scroll(management,'management')">
<a class="nav-link">MANAGEMENT</a>
</li>
<li class="nav-item waves-light" mdbRippleRadius [ngClass]="{'green-text': activeMenu=='contact'}" routerLink="/contact"
(click)="scroll(contact,'contact')" (scroll)="scrollHandler($event)">
<a class="nav-link">CONTACT</a>
</li>
</ul>
</links>
</mdb-navbar>
</section>
<div class="text-center">
<div #about>
<app-about></app-about>
</div>
<div #features>
<app-features></app-features>
</div>
<div #management>
<app-management></app-management>
</div>
<div #contact>
<app-contact></app-contact>
</div>
</div>
头文件.component.ts
scroll(el,name) {
this.activeMenu = name;
this.el =el;
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
上面的这个函数让我在点击菜单项时滚动到正确的 div。
问题是:1)当我滚动到同一页面上的不同组件时,我无法将菜单更改为活动状态。2) URL 不变。
提前致谢。
解决方案
基本上您需要在组件位置到达特定位置时触发或调用该方法。
import { Directive, HostListener, Input , ElementRef} from '@angular/core';
@Directive({
selector: '[appTrackScroll]'
})
export class TrackScrollDirective {
@Input("appTrackScroll")
private scrollName;
state = 'hide'
constructor(public el: ElementRef) { }
@HostListener('window:scroll', ['$event'])
checkScroll() {
const componentPosition = this.el.nativeElement.offsetTop
const scrollPosition = window.pageYOffset
// You can set the position as per your rquirement.
if (scrollPosition >= componentPosition) {
// Enable the menu
} else {
// Disable the menu
}
}
}
推荐阅读
- python - 如何减少我的 Django 应用程序的查询量?
- list - F# 中某个类型的 List 成员是否需要显式缓存
- python - 需要在字符串中获取子字符串例如:世界通过描述颜色非常美丽:蓝色和水,空气,火等,
- django - Django:进行复杂注释和聚合的问题
- java - Java Spring-boot:查找资源的问题
- php - 如果另一个多维数组中存在数组值,如何检查和替换数组
- button - 在 v-on:click 或 @click (Vue.js) 中的函数上传递变量
- java - 迭代时如何修改列表中的对象?
- python - 我们如何在 pytest 中接受一个命令行选项的多个值
- javascript - 有没有办法使用在位于子文件夹中的后台运行的 php 脚本的输出来更改 div 背景颜色?