我想使用id hashtag跳转到同一页面中特定部分的锚链接。这是我的HTML:
<div class="nav-container">
<ul class="nav text-center">
<li class="active">
<a href="#account-services">Services</a>
</li>
<li>
<a [routerLink]="['//account/'+account.account_id]" fragment="account-about">About</a>
</li>
<li>
<a href="#account-gallery">Gallery</a>
</li>
<li>
<a href="#account-reviews">Reviews</a>
</li>
</ul>
</div>
<div class="account-details">
<div id="account-services">
<h1>services</h1>
</div>
<div id="account-about">
<h1>About Us</h1>
</div>
<div id="account-store">
<h1>Store</h1>
</div>
<div id="account-gallery">
<h1>Gallery</h1>
</div>
<div id="account-reviews">
<h1>Reviews</h1>
</div>
</div>
ts组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-account-individual',
templateUrl: './account-individual.component.html',
styleUrls: ['./account-individual.component.css']
})
export class AccountIndividualComponent implements OnInit {
private fragment: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}
ngAfterViewInit(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) {
console.log(e);
}
}
}
答案 0 :(得分:0)
试试这个
this.route.fragment.subscribe(fragment => {
setTimeout(() => {
this.scrollTo(fragment);
}, 300);
});
答案 1 :(得分:0)
安装此包
ng2-page-scroll
导入app.module.ts
后
import {Ng2PageScrollModule} from 'ng2-page-scroll';
@NgModule({
imports: [
/* Other imports here */
Ng2PageScrollModule
]
})
export class AppModule {
}
并在您的组件html中进行测试
<a pageScroll href="#home">Testing</a>
<div id="home">
答案 2 :(得分:0)
像以前一样使用片段并绑定到click事件,如下所示:
在HTML中
<a fragment="account-about" (click)="navigateToSection('account-about')>About</a>
<div id="account-about">...</div>
在ts
public navigateToSection(section: string) {
window.location.hash = '';
window.location.hash = section;
}