以下の内容はhttps://karoten512.hatenablog.com/entry/2017/11/27/162522より取得しました。


Angular2/4にてjQueryを読み込んで使用する

Angular2/4にてjQueryを使いたい

どうしても使いたいときってありますよね。

0. プロジェクトを立ち上げる

ng new angular-jquery

1. index.htmlファイルにてjQueryを読み込む

<!-- index.html -->
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

2. AppComponentにて「アンビエント宣言」をする

/** app.component.ts */
import { Component } from '@angular/core';

declare var jquery:any;  // 追加
declare var $ :any; // 追加

declareは、アンビエント宣言と言います。

アンビエント宣言は、他のコンポーネント(例えば Web ブラウザや既存の JavaScript ライブラリ)から変数や関数などが提供されることをTypeScript コンパイラに伝えます。これは、既存の JavaScript ライブラリに静的型付けし、TypeScript で利用可能になることを意味します。

docs.solab.jp

3. app.component.tsにjQueryの処理を書き込む

/** app.component.ts */
export class AppComponent {
  title = 'angular 4 with jquery';
  toggleTitle(){
    $('.title').slideToggle();
  }
}

4. app.component.htmlに処理をbind

<h1 class="title" style="display:none">
  {{title}}
</h1>
<button (click)="toggleTitle()"> clickhere</button>

結果

f:id:karoten512:20171127162332g:plain

参考

stackoverflow.com

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

を行って導入する方法もあります。




以上の内容はhttps://karoten512.hatenablog.com/entry/2017/11/27/162522より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14