Angular подключить js файл
может кто-нибудь сказать мне, как использовать jQuery С Угловое?
Я знаю, что есть обходные пути, такие как манипулирование класс или id элемента DOM заранее, но я надеюсь на более чистый способ сделать это.
использование jQuery из Angular2-легкий ветерок по сравнению с ng1. Если вы используете TypeScript, вы можете сначала сослаться на определение jQuery typescript.
TypescriptDefinitions не требуются, так как вы можете просто использовать any в качестве типа $ или jQuery
в вашем угловом компоненте вы должны ссылаться на элемент DOM из шаблона, используя @ViewChild() после инициализации представления вы можете использовать nativeElement свойство этого объекта и pass на jQuery.
объявления $ (или jQuery ) как JQueryStatic даст вам типизированную ссылку на jQuery.
почему все делают это ракетостроение? Для всех, кому нужно сделать некоторые основные вещи на статических элементах, например, body tag, просто сделайте это:
- в индекс.HTML-код добавить script тег с путем к вашему jQuery lib, не имеет значения, где (таким образом, вы также можете использовать условные теги IE для загрузки более низкой версии jquery для IE9 и меньше).
- в своем export component блок имеет функцию, которая вызывает ваш код: $("body").addClass("done"); Normaly это вызывает ошибку объявления, так что сразу после всего импорта в этом .файл TS, добавить declare var $:any; и вы хорошо идти!
это то, что сработало для меня.
ШАГ 2-ИМПОРТ
в последнее время, я пишу код ES6 вместо typescript и в import без * as $ на import statement . Вот как это выглядит сейчас:
теперь это стало очень легко, вы можете сделать это, просто объявив переменную jQuery с любым типом внутри контроллера Angular2.
добавьте это сразу после операторов импорта и перед декоратором компонентов.
для доступа к любому элементу с идентификатором X или классом X вам просто нужно сделать
Шаг 1: Создайте демо-приложение angular 2
вы можете использовать любое имя. Теперь проверьте, работает ли он, запустив ниже cmd.(Теперь убедитесь, что вы указываете на "jQuery-demo", если не используете команду cd )
вы увидите "приложение работает!" в браузерах.
Шаг 2: Установите Bower (менеджер пакетов для интернета)
запустите эту команду на cli (убедитесь, что вы указываете на "jQuery-demo", если не используете команду cd):
теперь после успешной установки bower, создайте ' bower.файл json, используя следующую команду:
он будет запрашивать входы, просто нажмите enter для всех, если вы хотите по умолчанию значения и в конце типа "Да", когда он спросит: "хорошо выглядит?"
Шаг 3: Установите jquery
он создаст новую папку (bower_components), которая будет содержать папку установки jquery. Теперь у вас установлен jquery в 'bower_components' папка.
Шаг 4: Добавьте местоположение jquery в ' angular-cli.файл JSON'
открыть ' угловой-cli.файл json (присутствует в папке "jQuery-demo") и добавьте местоположение jquery в"Скрипты". Это будет выглядеть так:
Шаг 5: напишите простой код jquery для тестирования
"открыть".деталь.html ' файл и добавьте простую строку кода, файл будет выглядеть так:
теперь откройте приложение.деталь.ts' файл и добавить объявление переменной jQuery и код для тега "p". Вы также должны использовать lifecycle hook ngAfterViewInit (). После внесения изменений файл будет выглядеть так:
теперь запустите приложение angular 2 с помощью команды "ng serve" и протестируйте его. Это должно сработать.
I am not sure how to include JS files (vendors) after switching Angular Cli from SystemJs to Webpack.
For example
I have some js files that were installed via npm. Adding script tags to the head tag like this does not work. Nor does it seem like the best way.
Include these js files as part of the webpack bundle. This seems like the way it probably should be done. However I am not sure how to do this as all of the webpack code seems to be hidden behind the angular-cli-webpack node package. I was thinking maybe there is another webpack config that we might have access to. But I am not sure as I didn't see one when creating a new angular-cli-webpack project.
More Info:
The js files I am trying to include need to be included before the Angular project. For example jQuery and a third party js lib that isn't really setup for module loading or typescript.
Thanks for the link, but that isn't what I am looking for. That is for adding the definition files. I am trying to figure out what is the proper way to include thirdparty JavaScript libraries into my project.
Webpack angular2 example how to bundle different one for vendor one for polymorphism one for the app and one for the css to keep clean app.
External JavaScript in Angular 10 by Example
Let's now see how we can use external JavaScript in Angular 10. We'll make use of the popular jQuery library as an example.
Note: Please note that it's not recommended to use jQuery for maniplulating the DOM in Angular. This is simply an example of including an external JS library in Angular.
If your library is popular you'll most likely you can install it from npm. In you terminal, navigate to your project's folder and run install jquery:
Next, open the angular.json file and locate the scripts array and update as follows:
Next, in the component where you want to call your external library you need to declare the JavaScript symbol you want to call. For example, for jQuery, we need add the following line:
Next, you can call the required functions as in the following example:
Conclusion
In this tutorial, we've seen how to use external and custom plain JavaScript code and libraries in your Angular 10 (and previous versions) projects which is based on TypeScript.
Представляем вам перевод статьи Aditya Modi, опубликованной на blog.bitsrc.io. Статья посвящена использованию библиотеки jQuery в приложениях на Angular.
Нечасто я берусь за что-то с опаской. Однако в этот раз осторожность не помешает, ведь интегрировать jQuery в Angular не так-то просто.
Почему, собственно, я написал эту статью? Иногда jQuery действительно необходима для разработки на Angular, однако подобные JavaScript-фреймворки крайне редко связываются с этой библиотекой. Angular отвечает за рендеринг и управление DOM, и, внося в него изменения при помощи jQuery, вы рискуете получить крайне неожиданный результат.
Совет: используя Bit, вы сможете быстро делиться Angular-компонентами и повторно применять их в своих приложениях. Это позволит вам и вашей команде тратить меньше времени на создание новых приложений. Попробуйте.
Как бы там ни было, в некоторых ситуациях вмешательство в работу фреймворка необходимо, оправданно, оно может стать настоящим выходом из положения. Эти случаи не рассматриваются в моем блоге, однако, возможно, я расскажу о них в своих следующих статьях. А сейчас позвольте мне показать, как добавить библиотеку jQuery в Angular. В этом уроке я буду использовать VS Code. Вы можете выбрать какой-то другой редактор кода или загрузить Visual Studio Code для Windows, Linux и macOS.
9 Answers 9
Ideally you need to have .d.ts file for typings to let Linting work.
But It seems that d3gauge doesn't have one, you can Ask the developers to provide and hope they will listen.
Alternatively, you can solve this specific issue by doing this
If you use it in multiple files, you can create a d3gauage.d.ts file with the content below
and reference it in your boot.ts (bootstrap) file at the top, like this
Thanks. One more question, when will the declare var drawGauge: any; be referenced, at the moment of transpile this ts file? Or, put it in another way, when new drawGauge(this.opt) , how does the compiler know the drawGauge() is actually in d3gauge.js ?
Yes, on transpile, it has to know that there is/ or will be something named d3gauge . In second question, it doesn't, d3gauge.js assigns it to a global variable in the dom and that is from where it's being called on runtime.
just put in your index.html only, nowhere else, webpack solution probably doesn't work because of wrong path, but i don't know anything about webpack
@BingLu Hey man, did you get the solution working for you? I still got the EXCEPTION: Uncaught (in promise): Error: Error in someComponent saying that the declared variable is not defined and could not find a solution so far.
After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.
This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:
assets > testjs.js
include testjs.js in your index.html
index.html
In this tutorial, we'll learn how to use external and custom JavaScript libraries/code in Angular 10 projects which are based on TypeScript.
You will need to have the following prerequisites:
- Basic Knowledge of TypeScript and Angular,
- Node and NPM installed on your machine,
- Angular CLI 10 ( npm install -g @angular/cli ),
- An Angular project.
You can create an Angular 10 project by running the following command in your terminal:
In the recent versions of Angular, you'll be prompted by the CLI for a couple of questions such as if Would you like to add Angular routing? (y/N) and Which stylesheet format would you like to use?. You can answer these questions as you see fit because this won't affect how to use JavaScript libraries in your Angular project.
Интеграция jQuery в Angular
Первым делом нам нужно создать приложение на Angular, используя команду ng new . Далее с помощью команды cd переходим в папку, куда через npm будет установлена библиотека jQuery. Назовем получившееся приложение angularmeetsjquery .
Чтобы использовать jQuery CDN, достаточно просто создать ссылку на файл в теге script непосредственно из домена jQuery CDN. Код с функцией Subresource Integrity будет выглядеть следующим образом. (Как видите, я использую библиотеку jQuery версии 3.3.1.)
Делаем библиотеку jQuery глобальной
Файл jquery.min.js , находящийся в папке dis модуля jQuery, не является публичным (корректное название папки: dist. — Прим. ред.). Чтобы сделать библиотеку jQuery глобальной, переходим к файлу .angular-cli.json и прописываем в нем ссылку на путь к файлу jQuery.
При передаче ссылки на путь к файлу внутри Angular-приложения корневой папкой является src. Однако библиотека jQuery находится внутри каталога node_modules . Следовательно, нужно определить верный путь к файлу .angular-cli.json .
Чтобы убедиться в правильности пути, необходимо перейти в каталог node_modules→jquery→dist→jquery.min.js . Здесь можно увидеть указанный путь, а значит, для этого приложения библиотека jQuery была добавлена глобально. Не ждите, что страница localhost:4200 в вашем браузере перезагрузится самостоятельно, ведь файл находится вне папки src. Чтобы в приложении появились изменения, его придется перезапустить.
How to Use Custom JavaScript in Angular 10
Let's now see how we can use custom JavaScript in Angular 10 and previous versions.
First, create a JavaScript file inside the src/ folder, add the following code as example:
Next, add the script to the scripts array in the angular.json file:
You can also simply declare and call your JavaScript functions in any component since it's a TypeScript file. For example:
Используем jQuery в приложении на Angular
Затем вставляем хук жизненного цикла ngOnInit . Для этого можно импортировать OnInit из Angular Core.
Если нажать на кнопку, появится надпись «Wass Up».
Заключение
Добавление jQuery в Angular, а также использование этой связки — сомнительная идея.
Да, на первый взгляд метод кажется простым. Однако, как я уже говорил в начале статьи, сколь бы заманчиво ни выглядело совместное использование этих двух технологий, чаще всего затея оказывается плохой. В реальных Angular-приложениях приходится иметь дело с гораздо более сложными вещами, чем связанный с событием HTML-элемент button . Мой совет всем, кто работает с Angular и ищет возможность внедрить jQuery в свой TypeScript-код: если нет необходимости, не делайте этого. Желаю удачных экспериментов в области jQuery и Angular!
Шаг 1-Сначала первое
5 Answers 5
Last tested using angular-cli 11.x.x with Angular 11.x.x
This can be accomplished using scripts:[] in angular.json .
Note: As the documentation suggests in the global library installation: if you change the value of your styles (or scripts !) property, then:
Restart ng serve if you're running it,
..to see the scripts executed in a **globalcontext via the scripts.bundle.js file.
Note: As discussed in the comments below. JS libs that support UMD modules via es6 imports such as jQuery can also be imported into your typescript files using the es6 import syntax. For example: import $ from 'jquery'; .
BTW If the external file being added is a polyfill, then there is a dedicated mechanism for that nicely described in src/polyfills.ts (as of beta.31)
If you're using jQuery in your Angular project, then you're doing it wrong. I love jQuery, it took me far on my career, but if you're using Angular correctly, there is no more need for jQuery.
@BlairConnolly, While I agree and we would love to get rid of jQuery. We are consuming a Jquery UI from another team within our company whom doesn't have time to rewrite the whole UI at the moment. So sometimes people just don't have a choice.
@KrisHollenbeck I'm not trying to be a jerk but seriously consider the complexity of the tools we have accreted in order to adopt ES Modules. From transpilers, to frameworks, to loaders, to package managers, to bundlers, to CLIs we use incredibly complex, interdependent and often incompatible tools to leverage modules. We should be loath to do so if we throw away all the benefits. This should be a last resort approach, but will become de facto for users who don't understand why the complexity is even there, just accepting it.
There is a subtle difference to using scripts:[] then to adding something to the with . Scripts from scripts:[] get added to the scripts.bundle.js that gets always loaded in the body tag and will thus be loaded AFTER scripts in . Thus if script loading order matters (i.e. you need to load a global polyfill), then your only option is to manually copy scripts to a folder (e.g. with a npm script) and add this folder as an asset to .angular-cli.json .
So if you really depend on something being loaded before angular itself (Option A), then you need to copy it manually to a folder that will be included in the angular build and then you can load it manually with a in .
Thus, for achieving option a you have to:
- create a vendor folder in src/
- add this folder as an asset to .angular-cli.json :
copy your vendor script node_modules/some_package/somejs.js to vendor
However most of the time you only need this approach for packages, that need to be available globally, before everything else (i.e. certain polyfills). Kris' answer holds true for Option B and you get the benefit of the webpack build (Minification, Hashes, . ).
However if your scripts need not be globally available and if they are module-ready you can import them in src/polyfills.ts or even better import them only when you need them in your specific components.
Making scripts globally available via scripts:[] or via manually loading them brings it own set of problems and should really only be used, when it is absolutely necessary.
and in the corresponding template file, add
But it doesn't work, drawGauge can't be found.
- what're correct steps to import an external js file to angular2?
- since I'm using webpack, is it possible to do it in webpack? I refer to this question , the webpack solution there doesn't work for me as a result of .ensure can't be resolved.
Читайте также: