Angular 2 adding styling (css, js) - javascript

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>

Related

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.

Unable to use a selector of a sub-component in Angular

I want to "insert" task.component's view into my main app.component.html (root template) as follows:
(app.module.ts)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { TaskComponent } from './task/task.component';
#NgModule({
declarations: [
AppComponent,
TaskComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
(app.component.ts)
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'planner';
}
(task.component.ts)
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-task',
templateUrl: './task.component.html',
styleUrls: ['./task.component.css']
})
export class TaskComponent implements OnInit {
constructor() { }
ngOnInit() {
console.log("Task comonent initialized!");
}
}
(app.component.html)
<!--The content below is only a placeholder and can be replaced.-->
<app-task></app-task>
<div style="text-align:center">
<h1>
Welcome to {{ title + 1 }}!
</h1>
<img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
<li>
<h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
</li>
<li>
<h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
</li>
</ul>
So despite the fact that I have linked the task.component to the module I do not have access to its selector. Did I forget some import/export statements. Is that in fact a misunderstanding of angular's architecture/principle of structure?
The file task.component.html only consists of
<p>
task works!
</p>
Edit:
I also received the following error from the client's console:
[
What exactly shows in the place of the selector <app-task></app-task> that you added in app.component.html ?? What error in the console. This selector should work and be rendered to TaskComponent html view !!!!
To add a New Component to the Module that you're working on (which in your case is the AppModule), you first create a component(just use AngularCLI to do this by running the command ng g c task), and Angular CLI automatically adds it to your AppModule's declarations array. Then you can simply add the selector tag to your app.component.html to load that up
Just add <app-task></app-task> to your app.component.html
UPDATE
In some cases, even when you do everything properly, Angular doesn't recognise the Component that was added recently. Try breaking your local service by Ctrl + C on Windows or Cmd + C on Mac. And then run ng serve to serve up the App again. This generally happens when a Component is Added while the Server is running.
Here's a Sample StackBlitz for your ref just to cross check if you missed something.
I don't know what did you mean for linking components?
Following the structure that you shared it's working if you want see something, you must create the task-component.html because doesn't exist.
And the idea a component is that each component must has its logical indipendent to work.
And ways to share resources is using EventEmitters or binding properties.
This is the sceenshot that I saw and I can see the component created.
In fact restarting the server with ng serve did not solve the problem and therefore was not responsible for the missing interpolation of the component's template.
Rebuilding the app was the only (and ugliest) option for me which caused additionally work of course.
Delete all files of your project (all files in the layer in which amongst others node_modules is placed)
Setting up the project with ng new (...)
Building clean components with terminal commands (ng g c (...) / ng generate component (...))
Try re-running ng serve after stopping it. Hope you added component using Angular-Cli command -
ng generate component task

Separating the header/footer from content with Angular 4

I've started learning to use Angular and so far it seems fairly straight forward. I opted to convert one of my existing website themes over to familiarize myself with the process but ran into a question regarding proper usage.
My understanding thus far is that each page is a component. I have my index content in app.component.html, and then each sub page is a separate component as well. I would however like to separate the header/footer HTML and include it as I have in the past with PHP.
My question is, should the header/footer be individual components or should they just be singular HTML files, included using ng-include? I realize either would work but can't figure out which is the traditional implementation with Angular developers.
I am trying the following approach but the header/footer component's don't seem to load. They work fine from app.component.html but not from index.html.
index.html
<body>
<app-header></app-header>
<app-root></app-root>
<app-footer></app-footer>
</body>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { ProductComponent } from './product/product.component';
import { ProductsComponent } from './products/products.component';
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
ProductComponent,
ProductsComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You should create Header and footer components and use it in AppComponent.
This is helpful if you want to use i18n tools like translate or if you want to change the header or footer if user is logged in.
The app Structure should be something like this.
AppComponent
|
|----> HeaderComponent
|----> Router-Outlet ---> Page content should be in the container.
|----> FooterComponent
This is how you need to have the files. You cannot have the components in index.html as the angular bootstraps for app not for other components.

Angular2 - How module is different from component?

In the below code from ../src/app/app.module.ts,
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
Component consists:
view(../src/app/app.component.html)
logic(../src/app/app.component.ts)
style(../src/app/app.component.css)
Angular application is a tree of components. Good components have high cohesion, i.e. each component contains only elements with related functionality. They are also well encapsulated and loosely coupled.
How modules are different from components?
A component is just a class with the #Component() annotation. Note that .html and .css files might be referenced by the component, certainly not mandatory. The component template might very well be 'inlined' directly in the component configuration, or there simply might not be any html template at all for a given component.
A module is a structural element of an Angular application (and maybe other classes and interfaces). It is also "just a class" with the #NgModule() annotation.
It acts as a logical 'container' for your components, directives, services, pipes, etc... to help you structure your overall source code better.
You can have a look at this existing question : What's the difference between an Angular component and module
A module is something that has components. It wraps them up so you can import and manage them.
Notice when you make a component you can put anything that's decorated as #Injectable in your constructor:
#Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
constructor(private myService: MyService) { }
ngOnInit() {
}
}
And magically you will have a myService to use. This is dependency injection, which is built into Angular - but it's managed on a Module level. In your module you import what other modules you want to be able to use:
imports: [
BrowserModule,
FormsModule
],
define what your module includes:
declarations: [
AppComponent,
HeroesComponent,
MyService
],
export any components (so other modules can import them)
exports: [
HeroesComponent
],
They help organize an application into blocks of functionality. Components are things that tell angular how to render something. Modules compose Components, Pipes, Services etc into 'blocks' that can be compiled by angular or imported and used by others.
Edit to address comment
Taking your specific question about HttpClient. The HttpClient is the service you are using to perform the actions. The HttpClientModule is the module you import into your module, so you can use the service it contains.
You import the module:
#NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module
// after BrowserModule.
HttpClientModule,
],
})
And use the service:
#Component(...)
export class MyComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
...
}
The HttpClientModule contains within it all you need for the HttpClient to work, and packages it up so you can use it in your own projects.
This particular module only wraps up that one service, but the module could contain a bunch of related services, components, pipes or directives. For example, the RouterModule allows you to use the RouterOutlet and RouterLink directives.
Module in angular is set of Components, Services, Filters, or some another smaller modules too, or we can say where you import all these in order to use later in the app for future use. in a single app there can be one or more than one module may exist.
Whereas, A component controls a patch of screen called a view.
You define a component's application logic—what it does to support the view—inside a class. The class interacts with the view through an API of properties and methods.
Refer this guide for more details:
https://angular.io/guide/architecture

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

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>

Categories