3
1

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 5 years have passed since last update.

jQueryの処理はComponentに書く

Posted at

趣旨

angularからjQueryの処理を呼び出すためにはどうすればいい?
jQueryの処理を記載してみたものの、どうにも動かなくて困った...:thinking:
どこでつまづいたのか、どう対応したのかについて説明します。

つまづきポイント

angularに自動で読み込んでほしかったので、assets配下にコードとjQuery.jsを配置。

assets/common.js
// ロード時処理
$(function() {
    ...
});

開発ツールで確認。
コードもjQueryもangularによってscripts.bundle.jsにまとめられてる。
htmlのヘッダにscripts.bundle.jsの呼び出し宣言もつけてくれている。

…でも、どうにも実行されていないっぽい:disappointed_relieved:

対応

jQueryの処理は、Componentの中に書く!

そもそも宣言されてるだけでただの飾りになってるのでは?と思い
Component内に移植してやるとうまく動きました:relaxed:

main.component.ts
import { Component, OnInit } from '@angular/core';

// jQuery用の変数宣言
declare var $;

@Component({
  selector: 'main-component',
  templateUrl: './main.component.html'
})
export class MainComponent implements OnInit {
    ngOnInit(): void {
        // ロード時処理
        $(function() {
            ...
        });
      }
    }
}

そんな実装で大丈夫か?

自己解決した後、調べてみると普通に対応策書かれてましたね:laughing:
Angular2/4にてjQueryを読み込んで使用する

今回はindex.htmlにjQueryの呼び出し宣言書いてないから、
実装には微妙な違いがあったりするけど。

一番いい実装は型宣言ファイル引っ張ってくる方式なのかなぁ?

command
npm install jquery --save
npm install --save-dev @types/jquery

個人的には、jQueryは必要なComponentでのみ
明示的に変数宣言して使ったほうがいいんじゃないかと思います。

後からソースコードにgrepかけて、jQuery使ってるところを簡単に特定できるし:thumbsup:

declare var $;
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?