1-将模板引用变量添加到href标记,例如:
<a (click)="navigateTo('aboutus')" #aboutus><strong>ABOUT</strong></a>
2-使用ViewChild来获取href:
@ViewChild('aboutus') aboutusLink: ElementRef;
3-在此navigationTo函数中添加以下内容:
this.aboutusLink.nativeElement.scrollIntoView({behavior: 'smooth'});
避免在Angular中使用本机js选择器:)
,
尝试这样:
Working Demo
home.component.html
<app-header (Navigate)="navigateTo($event)"></app-header>
home.component.ts
@ViewChild("aboutus",{ static: false }) aboutus;
@ViewChild("contact",{ static: false }) contact;
navigateTo(element: string) {
this[element].nativeElement.scrollIntoView({ behavior: "smooth" });
}
header.component.ts
@Output() Navigate = new EventEmitter();
navigateTo(element: string) {
this.Navigate.emit(element)
}
header.component.html
<ul>
<li class="nav-item">
<a (click)="navigateTo('aboutus')" ><strong>ABOUT</strong></a>
</li>
<li class="nav-item">
<a (click)="navigateTo('contact')" ><strong>Contact us</strong></a>
</li>
</ul>
,
您可以使用df <- tibble(a = c(1,1,2,3,3),b = c('x','y','z','z'),c = c('ps','ps','qs','rs','rs'),d = c(100,200,300,400,500,600,700,800,900,1000,1100),strt = ymd(c('2019-03-20','2020-01-01','2018-01-02','2020-05-01','2016-01-01','2020-03-01','2020-01-02','2019-10-01')),fnsh = ymd(c('3019-03-20','3020-01-01','3018-01-02','2020-06-01','2016-05-01','2020-04-01','2020-06-10','2020-06-18','2019-11-01')))
进行有效编码。
现在// navigate.service.ts
import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
@Injectable({
providedIn: 'root',})
export class NavigateService {
navigate = new EventEmmiter<string>();
}
最后是// header.component.html
<ul>
<li class="nav-item">
<a (click)="navigateTo('aboutus')" >
<strong>ABOUT</strong>
</a>
</li>
<li class="nav-item">
<a (click)="navigateTo('contact')" >
<strong>Contact us</strong>
</a>
</li>
</ul>
// header.component.ts
import { Component } from '@angular/core';
import { NavigateService } from 'services/navigate.service'; // set path correctly
@Component({
selector: 'app-header',templateUrl: './header.component.html',})
export class HeaderComponent {
constructor(private navigateService: NavigateService) {}
navigateTo(status: string): void {
this.navigateService.navigate.emit(status);
}
}
现在,您可以在需要导航的地方致电服务。通过使用服务,您可以避免重复多余的代码。
本文链接:https://www.f2er.com/3074214.html