5
2

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.

HTMLのchangeイベントを強制発火させる

Last updated at Posted at 2020-07-08

次のような処理をした場合changeイベントは発火するのか

<!--HTML (Angular)-->
<div>
    <input type="text" id="hoge" (change)="hogeEvent()">
</div>
//TypeScript (Angular)

(document.getElementById('hoge') as HTMLInputElement).value = huga;

確認してみましたが、残念ながら発火してくれませんでした。というわけで次の行をTypeScriptに追加してあげましょう。

//TypeScript (Angular)

let event = new Event('change');
(document.getElementById('wegpunkte') as HTMLInputElement).dispatchEvent(event);

new Event('change')を生成してdispatchEventで発火させることで、changeと対応するイベント(例のコードではhogeEvent)が実行されます。

もし親要素にもchangeイベントがあって発火させたいのであれば、bubblesオプションで

let event = new Event('change',{bubbles:true});

と追加してあげれば祖先に当たる要素でも実行されます。

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?