![](/img/trans.png)
[英]How can I activate and deactivate styles in component from typescript from another component in Angular 6?
[英]How can I route from a component to a section of another component in Angular?
該標記在 component1 中聲明
<a [routerLink] = "['/c2']" fragment="c2id"> Link </a>
這是 component2 的變化
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-c2',
templateUrl: './c2.component.html',
styleUrls: ['./c2.component.css']
})
export class C2Component 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) {}
}
}
而你的component2 html會是這樣的
<p style="height: 800px;">
c2 works!
</p>
<hr>
<div id="c2id" style="height: 500px;">
The div with c2id
</div>
這是更新和工作的 stackblitz https://angular-fragment-example.stackblitz.io
我認為您正在尋找Fragments
。
官方文檔: Angular Docs-Query Params and Fragments
例子:
手動導航
在c1.html
<a [routerLink] = "['/c2']" [fragment]="c2id"> Link </a>
在c2.html
<div id="c2id">content</div>
程序化導航
在c1.ts
private fragmentSetDynamically: string;
constructor(private router: Router){}
onClickButton(){
this.router.navigate(['/c2'], {fragment: fragmentSetDynamically});
}
獲取片段:
在c2.ts
private fragment: string;
constructor(private activatedRoute: ActivatedRoute){}
ngOnInit(){
this.fragment = this.activatedRoute.snapshot.fragment;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.