LoginSignup
3
8

More than 3 years have passed since last update.

Angular で終了前に処理する

Last updated at Posted at 2017-10-30

コンポーネントを破棄する前に処理をする

  • Angular コンポーネントの Lifecycle Hooks の ngOnDestroy を利用する
// 任意のコンポーネント
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy { // ngOnDestroy を有効にするため OnDestroy の実装であることを宣言する
  ngOnDestroy() {
    // コンポーネント破棄前の処理
  }
}

ブラウザを閉じる前に処理をする

  • unload イベントのコールバックとして処理を登録する
  • unload はブラウザやタブを閉じようとした際やリロードの際に実行される
// 任意のコンポーネント
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @HostListener('window:unload', [ '$event' ])
  unloadHandler(event) {
    // ブラウザを閉じる前に実行したい処理を記述
  }

  @HostListener('window:beforeunload', [ '$event' ])
  beforeUnloadHandler(event) {
    // ついでにこちらはページ移動前の確認イベント
  }
}

3
8
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
3
8