How to load 3rd party css only required pages in Angular2 - javascript

I used pikaday.js and moment.js in Angular2.
In order to build with 3rd party libraries at Angular2, added script path to angular-cli.json.
I saw what how to build 3rd party library. Link is below.
https://github.com/angular/angular-cli#3rd-party-library-installation
I installed pikaday.js and moment.js.
$ npm install pikaday moment --save-dev
Then, I added scripts path, and css files path to angular-cli.json.
"app": [{
"styles": [
"styles.css",
"../node_modules/pikaday/css/pikaday.css",
"../node_modules/pikaday/css/site.css",
"../node_modules/pikaday/css/theme.css",
"../node_modules/pikaday/css/triangle.css",
],
"scripts": [
"../node_modules/pikaday/pikaday.js"
]
}]
That is success! angular-cli is really useful.
But, I found one problem.
Angular cli output 3rd party css that into html of the page using Angular2.
But there is a page that does not wanna use the library. Because, the page layout style was broken.
So, please tell me how to resolve this problem.
Thank you for any help you can provide.
Edit
I modified my component. below.
import {Component, OnInit, Input, ElementRef, ViewEncapsulation} from '#angular/core';
const pikaday = require('../node_modules/pikaday/pikaday');
const pikadayStyle = require('../node_modules/pikaday/scss/pikaday.scss');
#Component({
selector: '[appDatePicker]',
template: '',
styleUrls: [pikadayStyle],
encapsulation: ViewEncapsulation.None
})
export class DatePickerComponent {
// implement
}
Thank you VadimB.

I'm not sure if my solution can solve your particular problem as it depend how this library is structured inside, but for me this was a solution - I used require module loader;
var app = require('some-non-ES6-library');
Just try this first.
<script>
System.amdRequire();
System.amdDefine();
System.config({
...
});
</script>

Related

Import 2 Angular projects in another javascript project

I have 2 separated Angular projects.
For each of them, I run the following CLI command:
ng build --prod --output-hashing=none
It creates the following files for each project:
runtime.js
polyfills.js
main.js
Now I want to import the projects into another project, which is a simple javascript project (not Angular project).
I know that the order is important and that runtime.js and polyfills.js appear twice.
So I made sure that these files are the same (because I use the same Angular version in both projects).
The imports in the simple javascript project look something like this:
<script src="runtime.js"></script>
<script src="polyfills.js"></script>
<script src="main1.js"></script>
<script src="main2.js"></script>
Unfortunately, only one of the projects seems to work this way (and there are no exceptions).
If I'll import only main1.js or only main2.js they will work properly.
I guess the problem is the dependency libraries I use in each project, that maybe override each other, but I don't know what I can do about it.
UPDATE:
Not sure if it's relevant, but in each Angular project, I use #angular/elements in order to publish the components I need. something like this:
export class AppModule {
constructor(private injector: Injector) {
const elem = createCustomElement(MyFirstComponent, { injector });
customElements.define('my-first-element', elem);
}
ngDoBootstrap() {}
}
Then in the javascript project, I use it like this:
var elem1 = document.createElement('my-first-element');
container.append(elem1);
var elem2 = document.createElement('my-second-element');
container.append(elem2);
Check the <app-root></app-root> tag in your index.html.
You may need 2 different selector for your AppComponent:
// app.component.ts for the first project
selector: 'app-root-one',
// app.component.ts for the second project
selector: 'app-root-two',

How to Use External Javascript in TypeScript Angular

I want to use jquery and easypiechart js file's functions in typescript.
It doesn't work this way.
How to define these script what i specified in code as typescript ?
index.component.ts
import { Component, OnInit } from '#angular/core';
import * as $ from "../../../../../assets/plugins/jquery/jquery.min.js";
import { easyPieChart } from "../../../../../assets/plugins/easypiechart/jquery.easypiechart.min.js";
// these above 2 js files are defined in angular.json script section
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
constructor() {}
ngOnInit() {
//$(function(){
// $('.easypiechart').easyPieChart();
//});
// How to write this above script as typescript ?????????????????????
}
}
From the above question,it looks like jquery.easypiechart.min.js is the one that you need to use in your angular application as external js.
Put the js under assets folder say /assets/js/jquery.easypiechart.min.js
Goto your projects angular.json file and under scripts node of architect node put as an entry in the array.
"scripts": [
"./node_modules/jquery/dist/jquery.min.js",
"./src/assets/js/jquery.easypiechart.min.js" ]
Now you can refer the external js in any of your projects components
declare var $: any;// referencing jQuery library
#Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.scss']
})
export class IndexComponent implements OnInit {
constructor() {}
ngOnInit() {
$(document).ready(function () {
//accessing easypiechart.min.js.
$('.easypiechart').easyPieChart();
});
}
}
If you have included them in the scripts or index.html, you don't have to import them to the .TS file again
Use declare instead and it should work
What does 'declare' do in 'export declare class Actions'?
Instead of putting it in asset folder you should use it as node_modules dependency
For easy pie chart run this npm i easy-pie-chart --save & for jquery run npm i jquery
Normally you don't want to use jquery in Angular, because it usually implies to modify directly the DOM, which is a bad practice, but there is the way to do it: https://medium.com/all-is-web/angular-5-using-jquery-plugins-5edf4e642969
If you wanna plot a pie chart or other types of charts, you could use ng2-charts instead, it will allow you to use charts.js with Angular and Typescript.

How do I declare a dependency on an ng-metadata module?

I have a project that is using ng-metadata (https://github.com/ngParty/ng-metadata) to build a handful of Angular 1.5 modules. I have a test module/component that looks like this:
import { NgModule, Component, Inject, Input, Output, EventEmitter } from 'ng-metadata/core'
import { platformBrowserDynamic } from 'ng-metadata/platform-browser-dynamic'
#Component({
selector: 'test',
template: require('./test.template.html')
})
class TestComponent {
#Input() type: string;
constructor() {
console.log(`test: ${this.type}`)
}
}
#NgModule({
declarations: [TestComponent]
})
class HeroModule {}
platformBrowserDynamic().bootstrapModule(HeroModule)
Everything seems happy when compiled and I'm now attempting to use the module in another project (that is not using ng-metadata but has a compatible version of Angular).
I'm simply including the shims as directed by the ng-metadata docs and the JavaScript file that contains the module described above (built by webpack). I have a new module in this project that wants to list the HeroModule as a dependency. I've tried a few things:
// attempt 1:
angular.module('my-consuming-module', ['ui.router', 'hero'])
// attempt 2:
angular.module('my-consuming-module', ['ui.router', 'heroModule'])
// attempt 3:
angular.module('my-consuming-module', ['ui.router', 'hero-module'])
All always end up with the same Error: $injector:nomod Module Unavailable error from Angular.
If I'm using ng-metadata to build my modules, what are the names I use to list them as dependencies in another project?
Finally figured this out! It's amazing what happens when you carefully read documentation...
Found in the Manual Angular 1 Bootstrap section of ng-metadata's docs:
You can still leverage ng2 way of components registration without ng-metadata bootstrap, but you have to manually create your Angular 1 module from an ng-metadata #NgModule using the bundle helper function.
I ended up being able to do the following:
// REMOVED platformBrowserDynamic().bootstrapModule(HeroModule)
const Ng1AdminModule = bundle(HeroModule).name;
export const AppModule = angular.module('hero', [Ng1AdminModule]);
And then my hero module becomes accessible to the my-consuming-module just as I expected. The bundle helper function was the key to figuring this out.
You need to import those module from their respective locations and inject it inside your angular module
//ensure `angular`, `angular-ui-router` should be there in `map` of systemjs.config.js
import * as angular from 'angular';
import * as uiRouter from 'angular-ui-router';
import { heroModule} from './hero.module';
angular.module('app',[ uiRouter, heroModule]);
Check references here

Angular 2 adding styling (css, js)

I have a web style left from angular 1 which includes sass and and bundle of js libs (jquery, bootstrap, animo, etc...) is it possible to integrate them to angular 2? if so, then how? I tried including them into index.html, no errors and no style. I understand that components are view encapsulated. Do you just add them to systemjs and css in index.html?
Yes you can, check a sample code below that does exactly that. Of interest to you will be these lines of code:
styles: [
require('./app.component.scss')
],
encapsulation: ViewEncapsulation.None,
The first one imports sass file while the other line allows angular2 to apply the styles globally to the entire angular2 app.
import {
Component,
ViewEncapsulation,
OnInit
} from '#angular/core';
import {
ROUTER_DIRECTIVES,
} from '#angular/router';
#Component({
moduleId: module.id,
selector: 'ch',
templateUrl: 'app.component.html',
styles: [
require('./app.component.scss')
],
encapsulation: ViewEncapsulation.None,
directives: [
ROUTER_DIRECTIVES,
],
providers: [
]
})
export class AppComponent{
}
For JS libs the best strategy would be to include them using npm install {yourlibs} --save then add them to systemjs build config file. Check this url for more information on how to go about it https://github.com/angular/angular-cli/wiki/3rd-party-libs#adding-underscore-library-to-your-project
for external libs just include them on page and use declare let somelib; syntax after import statements
import {something} from 'sometbing';
declare let somelib;
#Component({...})
export class tralala{
somemethod(){
somelib.somethibg();
}
}
and in index.html for example
<script src="somelib.js"></script>

Angular2: how to use bootstrap-tagsinput properly

I'm trying to use bootstrap-tagsinput library in my Angular2 project. The library is installed using package.json file:
"dependencies": {
...
"bootstrap-tagsinput": "^0.7.1",
...
}
Now I have a bootstrap-tagsinput folder in node_modules. I want to use tagsinput in a specific component. I saw there is a bootstrap-tagsinput-angular.js file in the node_modules/bootstrap-tagsinput/dist directory, but I can't managed to use it properly.
Am I supposed to add the JS file in my index.html so bootstrap-tagsinput will be available for all components? Or is there a way to import it just where it is needed?
In other way, is there a way to do something like this:
mycomponent.component.html:
<input type="text" value="Amsterdam,Washington,Sydney,Beijing,Cairo" data-role="tagsinput"/>
mycomponent.component.ts:
import {Component, AfterViewInit} from '#angular/core';
import {TagsInputComponents} from 'bootstrap-tagsinput'; // Something like that?!?
#Component({
...
})
export class MyComponentComponent implements AfterViewInit {
ngAfterViewInit():any {
$('input').tagsinput('refresh');
}
}
thanks a lot for your help!
I can see some issue in using bootstrap-tags-input with angular batter to use ngTagsInput if you using angular.
Please see more details at : ngTagsInput , demo
the boostrap-tagsinput is a directive. So you can need somethings as follow:
Step 1: Import boostrap-tagsinput
import {TagsInputComponents} from 'bootstrap-tagsinput';
Step 2: Add to directives
#Component({
...
directives: [TagsInputComponents],
...
})
then use it in your view.
Hope this help!
For anyone looking for an easier solution. I ended up using angular2-tag-input
First you'll have to run your node command prompt
npm install angular2-tag-input --save
Then include it in your module
// In one of your application NgModules
import {RlTagInputModule} from 'angular2-tag-input';
#NgModule({
imports: [
RlTagInputModule
]
})
// In one of your component templates
<rl-tag-input [(ngModel)]="tags" placeholder="Testing placeholder"></rl-tag-input>
// In one of your component ts file
var tags= ['tag1','tag2','tag3']

Categories