【问题标题】:Angular 10. How to navigate to a component's sections via a different component's anchor link tag?Angular 10. 如何通过不同组件的锚链接标签导航到组件的部分?
【发布时间】:2021-02-08 05:48:53
【问题描述】:

app.component.html

<!--I wish to keep this structure like this, because menu.component has position sticky at top: 0-->
<app-home></app-home>
<app-menu></app-menu>
<app-about></app-about>
<app-projects></app-projects>
<app-contact></app-contact>
<app-footer></app-footer>

menu.component.html

<!--On anchor link click, navigate to corresponding  component-->
<nav>
    <a>Home</a>
    <a>About</a>
    <a>Projects</a>
    <a>Contact</a>
</nav>

home.component.html、about.component.html、projects.component.html、contact.component.html

<!--Basic structure-->
<section>
    <p>component works!</p>
</section>

网站基本结构的链接 https://stackblitz.com/edit/angular-ivy-ufce4g

我会分享一个指向实际网站(我的个人网站)的链接,但我不知道我是否被允许。

【问题讨论】:

  • 你看过 Angular 路由器吗?我相信这就是你想要的。见angular.io/guide/router
  • 我希望在不使用 的情况下渲染 app.component.html 中的所有组件。因为否则路由器只会渲染一个组件。并从我的 menu.component.html 锚点上单击以将相应的组件滚动到窗口顶部,就像本机锚点 href 行为一样。

标签: html angular typescript sass anchor


【解决方案1】:

一种解决方案是在您的menu 组件和您的app 组件之间创建一个共享服务。

它会像这样工作:

  1. menu 组件中单击导航项时发送通知;
  2. 在您的应用程序组件中监听通知。收到新通知时,滚动到页面上的相应组件。

类似这样的:

@Injectable({
  providedIn: 'root'
})
export class NavigationService {
  private _navigation$ = new BehaviorSubject<string>('home');
  navigation$ = this._navigation$.asObservable();

  constructor() { }

  updateNavigation(item) {
    this._navigation$.next(item);
  }

}

在您的menu 组件中,每当单击导航项时调用NavigationServiceupdateNavigation 方法。

@Component({
  selector: 'app-menu',
  // ...
})
export class MenuComponent {

  constructor(private navigationService: NavigationService) {}

  // Call this method whenever one of your navigation items is clicked
  // in your template.
  // 
  // navigationItem could, for example, be a string/enum corresponding to
  // the component that must be scrolled into view
  handleNavigationItemClick(navigationItem: string) {
    this.navigationService.updateNavigation(navigationItem);
  }
}

最后,在您的 app 组件中,监听导航项更新并滚动到该组件。

@Component({
  // ...
})
export class AppComponent implements OnInit {

  constructor(private navigationService: NavigationService) {}

  ngOnInit() {
    this.navigationService.navigation$.pipe(
      distinctUntilChanged(),
    ).subscribe(navigationItem => this.scrollIntoView(navigationItem))
  }

  private scrollIntoView(component) {
    // Scrolling logic ...
  }
}

【讨论】:

  • rxjs 超过了我。我阅读了一些有关在组件之间共享通信的最佳实践的主题。并且有非常不同的方法。对于我的问题,我基本上只是通过 @ViewChild(Component) 导入了我需要的 app.component.ts 中的组件,为菜单按钮附加了一个 onclick 侦听器,然后通过 if 语句滚动查看相应组件的元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 2019-05-02
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
相关资源
最近更新 更多