2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AngularでURLからURLハッシュを取得する方法

Last updated at Posted at 2019-11-18

ここで言う**URLハッシュ(url hash)**というのはページ内リンクを踏んだときにURLに#から始まる文字列で表されるアレのことです。URLフラグメント(url fragment)とも言います。
(例: https://myblog.com/page1#intro#intro)

結論

ActivatedRoutefragmentプロパティを参照しましょう。fragmentの型はObservable<string>です。

StackBiltzのサンプル

app.component.ts
@Component({
  selector: 'app-root',
  template: `
    <div>Current URL fragment: {{ fragment | json }}</div>
    <div id="url-fragment"></div>
    <a routerLink="/" fragment="url-fragment">Jump to the URL fragment</a>
  `
})
export class AppComponent implements OnInit {
  fragment: string;

  constructor(private route: ActivatedRoute) { }
    
  ngOnInit(): void {
    this.route.fragment.subscribe(fragment => {
      console.log(`ActivatedRoute.fragment: ${fragment} (typeof: ${typeof fragment})`);
      console.log(`window.location.hash: ${window.location.hash}`);
      this.fragment = fragment;
    });
  }
}

注意点

StackBuiltzのサンプルを動かしてみるとわかりますが、URLにURLハッシュが含まれない場合、このfragment空文字列が流れた後、nullが流れます。
また、window.location.hashと異なり、先頭の**#**は含まれません。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?