Link到Angular9中不同页面的具体内容

Link to specific content of different page in Angular 9

假设网页上有三个类别 - Continent、Country、State。 我目前正在处理一个放在不同页面上的按钮。我希望当单击按钮时,我的页面将自动重定向到类别页面并滚动到第三部分,即状态部分。 我对 Angular 有点陌生,并且尝试了很多在其他网站上提到的方法,例如使用 RouterLink、导航、路线,但没有任何效果符合我现在的预期。 有人可以为此提供帮助或分享一些已经开发的链接。

提前致谢。

很简单。在第一页这样在路由器中传递状态

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

<br>
<br>

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

然后在第二页,使用activated route从router获取状态对象。使用 ViewChild 装饰器与 DOM 进行通信。在ngAfterInit中订阅Activated Route params Observable,获取自己需要的参数,滚动到视图中。查看下面的代码片段以了解我的意思

@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()
      }
    })

  }

}

在第 2 页 Html 创建一个选择器。在这个例子中,我制作了我的选择器容器。然后给你的每个部分一个id。 id 是你的伤口滚动到的地方。 您的 html 应如下所示。

<div #container>

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

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

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

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