概要
- Angular でルーティン後に自動で別サイトにリダイレクトするサンプルを作成する。
用途
- ルーティング後にFormの内容をPOSTして別サイトにリダイレクトしたいケース
- POSTしたいデータについてをAngular内で取得して設定したいケース
実装方針
- テンプレート側に
<form> を用意する。
<form> にはリダイレクト先のURLを action に設定する。
ViewChild で HTMLFormElement の参照を取得する。
ngAfterViewInit 内で HTMLFormElement を submitしてルーティング後にリダイレクト処理を発生させる。
実行環境
使用ライブラリ
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<form #f action="./assets/redirect.html" method="POST">
<input type="hidden" name="id" [value]="data.id" />
<input type="hidden" name="name" [value]="data.name" />
<input type="hidden" name="memo" [value]="data.memo" />
</form>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('f', { static: false }) form: ElementRef<HTMLFormElement>;
data = {
id: '1',
name: 'Bob',
memo: 'memo2',
};
ngAfterViewInit(): void {
this.form.nativeElement.submit();
}
}
github.com