LoginSignup
16
10

More than 5 years have passed since last update.

angular2でページ読み込み後に処理を実行する方法

Posted at

困ったこと

Angular2で「全ての要素が読み込まれた後に特定の処理を行いたい」と思ったものの、要素が見つからない

具体的には
id="video"の動画が再生終了したタイミングを検知して、動画の内容を入れ替えたい。しかし、要素が見つからないというエラーが出る。
という状態でハマったので解決策をメモしておきます。
(調べつつ最初に見つけた解決策ですので、他に良い方法があるかもしれません)

原因

javascriptではありがちなのですが、要素が読み込まれていない状態(DOMの構築待ち)でスクリプトを実行してしまっているのが原因みたいです。

解決策

公式ドキュメントを見るとAfterViewInitというフックがあるようです。

stackoverflowでは下記のように
1.importに追記
2.implementsに追記
3.Class内にngAfterViewInit()として処理を追記
と書かれています。

import {Component, AfterViewInit} from 'angular2/core';

@Component({
  selector: 'home',
  templateUrl: './components/home/home.html'
})
export class HomeCmp implements AfterViewInit {


    ngAfterViewInit() {
       //Copy in all the js code from the script.js. Typescript will complain but it works just fine
    }

おまけ

今回やりたかった「id=videoの動画が再生終了したことを検知する処理」はこれです。

  ngAfterViewInit() {
    var mVideo = <HTMLVideoElement> document.getElementById('video');
    mVideo.addEventListener("ended", function(){
      console.log("動画が終了しました"); //ここに要素入れ替えのスクリプトを書く
    }, true);
  }
16
10
1

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
16
10