【问题标题】:Link to specific content of different page in Angular 9链接到 Angular 9 中不同页面的特定内容
【发布时间】:2021-04-20 12:08:17
【问题描述】:

假设网页上有三个类别 - 大陆、国家、州。 我目前正在处理已放置在不同页面上的按钮。我希望当单击按钮时,我的页面将自动重定向到类别页面并滚动到第三部分,即状态部分。 我对 Angular 有点陌生,并且尝试了很多在其他网站上提到的方法,比如使用 RouterLink、导航、路由,但没有按照我现在的预期工作。 有人可以帮忙或分享一些已经开发的链接。

提前致谢。

【问题讨论】:

  • 你能分享你的代码吗?

标签: angular redirect routes navigation angular-ui-router


【解决方案1】:

这很容易。在第一页像这样在路由器中传递状态

<button [routerLink] = "['/page2', {pageSec: 'section2'}]">Go to section 2</button>

<br>
<br>

<button [routerLink] = "['/page2', {pageSec: 'section3'}]" >Go to Section 3</button>

然后在第二页,使用激活的路由从路由器获取状态对象。使用 ViewChild 装饰器与 DOM 进行通信。订阅 ngAfterInit 中的 Activated Route params Observable,获取你需要的参数,然后滚动到视图中。检查下面的 sn-p 以了解我的意思

@Component({
  selector: 'app-page2',
  templateUrl: './page2.component.html',
  styleUrls: ['./page2.component.scss']
})
export class Page2Component implements AfterViewInit {
  constructor(private http: HttpClient, private activeRoute: ActivatedRoute, ) { }
  @ViewChild('container') container: ElementRef<HTMLElement>;

  ngAfterViewInit(): void {

    this.activeRoute.params.subscribe(param => {
      // alert(param.pageSec)
      if(param.pageSec){
        const section = this.container.nativeElement.querySelector(`#${param.pageSec}`)
        console.log(section)

        section?.scrollIntoView()
      }
    })

  }

}

在 Page2 Html make 和一个选择器上。在这个例子中,我制作了我的选择器容器。然后给你的每个部分一个id。 id 是您的伤口滚动到的内容。 您的 html 应如下所示。

<div #container>

  ............
  <div id="section1">
    .......
  </div>

  <div id="section2">
    ....
  </div>

  <div id="section3">
    .....
  </div>
</div>

就是这样!!!!确保使用 ngAfterInit 而不是 ngOninit,因为初始化组件后 Dom 元素不会立即可用

【讨论】:

  • 谢谢哥们。它就像魅力一样。我几乎花了 12-13 个小时才把它贴在这里,但没有奏效。现在它工作正常。
  • 你能告诉我这个概念已经被征用的 Angular 文档吗?
  • 嘿伙计,这个概念真的没有文档。在此之前我需要做这样的事情,为什么我知道。大多数 Angular 的 api 都与 rxjs 有关,所以如果你在项目中使用 rxjs,使用 angular 会很容易。同样,无论何时您想使用 dom,只要知道您可能必须使用 viewchild 装饰器。您可以阅读 rxjs 和装饰器。
猜你喜欢
  • 2011-04-23
  • 2011-09-28
  • 2017-06-16
  • 2021-04-09
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
相关资源
最近更新 更多