How to include dataTable to angular 2 application? - javascript

I have a simple application in angular 2. I want to display data in a paginated table. I found this example very nice and I would like to use in my app.
Thehtml of the example is in home.component.html,
The css of the example is in script in index.html like:
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.2.2/css/select.dataTables.min.css">
I want to know where I should put the java script code for this to work. I have tried to put in index.html and home.compose.html, but none on this worked correctly.
Please tell me where the java script code should go.
Thank.
This is the javascript:
$(document).ready(function() {
$('#example').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
} );
} );

If you already took reference of Jquery in your Html page than no need to import it in component.ts file. See the below code it is working fine for me.
import { Component, OnInit, ViewChild } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { Observable } from 'rxjs/Rx';
import { Global } from '../shared/global';
declare var $ : any;
#Component({
templateUrl: 'app/Component/assignfeatureview.component.html'
})
export class AssignFeatureViewComponent {
constructor() {
}
ngOnInit() {
$(document).ready(function () {
$('#tblAssignFeature').DataTable();
});
}
}

Try to use Angular compatible version of that, if still want to use them, if it's used in one Component, then just put the piece of code in ngOnInt in your component, also use import to import the code in your component, something like this:
import {Component} from "#angular/core";
import {$} from "jquery";
//also import the datatables plugin for jQuery
#Component({
selector: "app",
templateUrl: "app.html",
styleUrls: ["jquery.dataTables.min.css", "select.dataTables.min.css"]
});
export class LoginComponent {
constructor() {
}
ngOnInit() {
$('#example').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]]
});
}
}

import {Component} from "#angular/core"; import {$} from "jquery";
//also import the datatables plugin for jQuery
#Component({ selector: "app", templateUrl: "app.html",
styleUrls: ["jquery.dataTables.min.css",
"select.dataTables.min.css"] }); export class LoginComponent {
constructor() { }
ngOnInit() {
$('#example').DataTable( {
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
} ],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]] }); }
}

Related

Uncaught CKEditorError: ckeditor-duplicated-modules in angular 11

i want to use Ckeditor and Ckfinder thgother in angular .
i u use by this way :
Module :
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { BrowserModule } from '#angular/platform-browser';
import { CKEditorModule } from '#ckeditor/ckeditor5-angular';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
CKEditorModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and this is my component :
import { Component, OnInit } from '#angular/core';
import * as ClassicEditor from '#ckeditor/ckeditor5-build-classic';
import CKFinder from '#ckeditor/ckeditor5-ckfinder/src/ckfinder';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
public Editor = ClassicEditor;
ngOnInit(): void {
ClassicEditor
.create(document.querySelector('#editor'), {
plugins: [CKFinder],
// Enable the "Insert image" button in the toolbar.
toolbar: ['uploadImage' ],
ckfinder: {
// Upload the images to the server using the CKFinder QuickUpload command.
uploadUrl: 'https://example.com/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&responseType=json'
}
});
}
}
and this is Html Code :
<ckeditor [editor]="Editor" [config]="{ toolbar: [ 'heading','ckfinder', '|', 'bold', 'italic' ] }"
data="<p>Hello, world!</p>"></ckeditor>
but it show me this error:
Uncaught CKEditorError: ckeditor-duplicated-modules
whats the problem ? how can i use the Ckfinder in angular ?
You can use the official CK Editor 5 Angular component.
Documentation: https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/angular.html
GitHub:
https://github.com/ckeditor/ckeditor5-angular
You can create a custom build using Online Builder tool with all the required plugins and then import that build in angular.
I have been using the custom build with custom plugins without any issues.

Ag-grid custom tool tip component doesn't work

My custom tooltip is pretty simple
custom.ts file
import { Component } from '#angular/core';
import {ITooltipAngularComp} from 'ag-grid-angular';
#Component({
selector: 'app-custom-columnheader-tooltip-component',
templateUrl: './custom-columnheader-tooltip-component.html',
styleUrls: ['./custom-columnheader-tooltip-component.css']
})
export class CustomColumnheaderTooltipComponent implements ITooltipAngularComp {
private params: any;
agInit(params): void {
console.log("test tooltip");
this.params = params;
}
}
custom.html file:
{{params.value}}
I imported the component in app.module.ts file and added it as part of declarations and withComponents
app.module.ts file:
import {CustomColumnheaderTooltipComponent} from '...';
declarations: [
CustomColumnheaderTooltipComponent],
imports: [AgGridModule.withComponents([CustomColumnheaderTooltipComponent])]
my main component which calls this custom tooltip is as follows:
main.ts
frameworkComponents = {
customTooltip: CustomColumnheaderTooltipComponent}
IN my default col Definitions:
defaultColDef: ColDef = {
enableRowGroup: true,
filter: true,
resizable: true,
sortable: true,
autoHeight: true,
valueFormatter: this.cellValueFormatter.bind(this), // numeric formatting
cellRenderer: this.cellRenderer,
headerTooltip: 'hi',
tooltipComponent:'customTooltip'
};
I was hoping the header tooltip string will be picked up by the tool tip component and it is displayed as a part of that component as 'header name: hi' but my application just displays 'hi' as the tool tip. I cant see the console logging within the agInit() , basically it doesn't connect to that component for the tool tip. Any suggestions are highly appreciated.
Looks like you have problem in registering your custom tooltip
In my app.module.ts
I would do something like below -
imports: [
BrowserModule,
FormsModule,
AgGridModule.withComponents(
[CustomColumnheaderTooltipComponent]
)
],
declarations: [
............,
CustomColumnheaderTooltipComponent,
...........
],
Check this github example from official ag grid doc

How to import jQuery code in to Typescript

I have Typescript code and I want to add jQuery code inside my Typescript code for MEAN Stack
$('.chips').chips();
$('.chips-initial').chips({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
$('.chips-placeholder').chips({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
});
TypeScript Code :
import { Router } from '#angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
constructor() { }
ngOnInit() {
}
onLogoutClick() {
localStorage.removeItem('user');
this.fmService.show('Successfully logged-out', {
cssClass: 'alert-success',
timeout: 3000
});
this.router.navigate(['/']);
}
}
I want to add previous details in my Typescript code. Help me to do this using jQuery code.
Step: 1
Include jquery file in angular.json file:
.
.
"scripts": [
"src/assets/js/core/jquery.min.js"
],
.
.
Step: 2
Declere $ vairable in ts file before #component devorated
declare var $: any;
#Component({
.
.
OR
import * as $ from "jquery";

How implement Chart.js in Angular 2?

I am using the latest version of Angular 2, V4.0.0 and I want to use graphs from the Chart.js library in my project without many complications.
How can I implement Chart.js in my angular project that does not give me problems in the final production?
You can implement Chart.js in a simple way with the following instructions:
1. Create a new project with angular-cli, skip if you already have one created
ng new example-chartjs
2. Install Chart.js in your project
npm install chart.js --save
3. Import Chart into its component
import Chart from 'chart.js';
4. Use Chart in your view and component
In your view:
<canvas id="myChart" width="400" height="400"></canvas>
In your component:
ngOnInit() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {...});
}
The component should look similar to the following
import { Component, OnInit } from '#angular/core';
import Chart from 'chart.js';
#Component({
selector: 'app-chart',
templateUrl: './chart.component.html'
})
export class DashboardComponent implements OnInit {
constructor() { }
ngOnInit() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {....});
}
}
Another alternative to use is to include the library from the file ".angular-cli.json"
1. Include in the scripts the library
"styles": [
"styles.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/chart.js/dist/Chart.min.js"
]
2. Declare a variable of type "any" in the controller
declare var Chart:any;
3. Use Chart in your view and component
In your view:
<canvas id="myChart" width="400" height="400"></canvas>
In your component:
ngOnInit() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {...});
}
The component should look similar to the following
import { Component, OnInit } from '#angular/core';
declare var Chart:any;
#Component({
selector: 'app-chart',
templateUrl: './chart.component.html'
})
export class DashboardComponent implements OnInit {
constructor() { }
ngOnInit() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {....});
}
}
First
npm install chart.js --save
Second
npm install #types/chart.js --save
Third - import Chart into component this way
import * as Chart from 'chart.js';
I've implemented the Chart.js on Angular at this way(first you'll need to install it using npm install chart.js --save):
The folder structure of my project
src/
assets/
app/
charjs/
services/
First I've created a service called report.service.ts :
src/app/services/report.service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ReportService {
constructor(public http: Http) {
}
getReports() {
return this.http.get('assets/report.json')
.map(res => res.json());
}
}
This service it's created based on Angular tutorial showing how to get an external file(or link) and retrieve Json data.
This is important to collect the data from external source(if you must)
The difference between a service and a component, It's you need to to insert this service as a provider on the app.module.ts :
src/app/app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { HttpModule, JsonpModule } from '#angular/http';
import { ReportService } from './services/report.service';
import { ChartjsComponent } from './chartjs/chartjs.component';
#NgModule({
declarations: [
AppComponent,
ChartjsComponent
],
imports: [
BrowserModule,
HttpModule,
JsonpModule
],
providers: [ReportService],
bootstrap: [AppComponent]
})
export class AppModule { }
After that I've created the component chartjs.component.js , and used AfterViewInit instead of OnInit. I've used this approach because our service retrieves the data in asynchronous and, because of that, the data can be returned before the view has been initiated.
src/app/chartjs/chartjs.component.ts
import { Component, AfterViewInit,ViewChild, ElementRef } from '#angular/core';
import Chart from 'chart.js';
import { Respon2se } from '#angular/http';
import 'rxjs/add/operator/map';
import { ReportService } from '../services/report.service';
#Component({
selector: 'app-chartjs',
templateUrl: './chartjs.component.html',
styleUrls: ['./chartjs.component.css']
})
export class ChartjsComponent implements AfterViewInit {
#ViewChild('graphcanvas') mycanvas:ElementRef;
createData;
chartOptions;
constructor(public reportService: ReportService) {
}
ngAfterViewInit() {
this.reportService.getReports().subscribe(reportsData => {
this.createData = {
labels: 'Scatter Dataset',
datasets: [{
label: "reportRetrieve",
data: reportsData,
}]
};
this.chartOptions = {
legend: {
display: false,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: "black"
},
scaleLabel: {
display: true,
labelString: "Report Size",
fontColor: "red"
}
}],
yAxes: [{
gridLines: {
color: "black",
display: false
},
scaleLabel: {
display: true,
labelString: "Chart Report",
fontColor: "green"
}
}]
},
layout: {
padding: {
left: 0,
right: 50,
top: 50,
bottom: 0
}
},
maintainAspectRatio: false
};
let ctx = this.mycanvas.nativeElement.getContext('2d');
new Chart(ctx, {
type: 'bubble',
data: this.createData,
options: this.chartOptions,
responsive: false
});
});
}
}
A few comments about this file;
. After imported the service, I've used subscribe,to allow charjs library to get the data and push it on new Chart
. ChartOptions its just a variable to change the chart view the way you want, I've used to create a bubble chart.
. You can define if it's responsive or not.
After you've done that, you'll need to set your html:
src/app/chartjs/chartjs.component.html
<div style="height: 600px;width: 600px">
<canvas #graphcanvas></canvas>
</div>
I hope that helps someone who couldn't implement on the other ways.
I believe, on Angular, chartjs will work like below, because context is available afterViewInit() not onInit()
import { Component, ViewChild, ElementRef, AfterViewInit} from '#angular/core';
import Chart from 'chart.js';
#Component({
selector: 'app-statistics',
templateUrl: './statistics.component.html',
styleUrls: ['./statistics.component.css']
})
export class StatisticsComponent implements AfterViewInit{
#ViewChild('myChart') Chart: ElementRef;
constructor() {
}
ngAfterViewInit() {
var ctx = this.Chart.nativeElement.getContext('2d')
var myChart = new Chart(ctx,{...})
}
}

JQuery plugin is not working with Angular 2

as i am new to angular2 i am expecting to find out a solution for the following scenario.
The jQuery plugin is not working after getting the data -http://www.owlcarousel.owlgraphic.com/
i got issues on *var owl = jQuery(this.elementRef.nativeElement).find('#breif');
owl.owlCarousel();
My full code are given bellow
angular 2 component:
/ beautify ignore:start /
import {Component, OnInit , ElementRef, Inject } from '#angular/core';
import {FORM_DIRECTIVES} from '#angular/common';
import {CAROUSEL_DIRECTIVES} from 'ng2-bootstrap/components/carousel';
/ beautify ignore:end /
import {Api} from '../../../../services/api';
declare var jQuery:any;
#Component({
selector: 'breif',
directives: [CAROUSEL_DIRECTIVES],
template: require('./template.html')
})
export class BreifComponent implements OnInit {
elementRef: ElementRef;
breifs: Object;
public myInterval:number = 5000;
public noWrapSlides:boolean = false;
public slides:Array<any> = [];
constructor(#Inject(ElementRef) elementRef: ElementRef , private api: Api) {
this.elementRef = elementRef
this.loadBreif();
}
ngOnInit() {
**var owl = jQuery(this.elementRef.nativeElement).find('#breif');
owl.owlCarousel();**
}
loadBreif(){
this.api.getBreif().subscribe(
data => {
this.breifs = data.result.articles;
},
err => console.error(err),
() => {
}
)
}
}
template.html
<div class="owl-carousel" id="breif" >
<div class="item" *ngFor="let breif of breifs"><h4>{{breif.title}}</h4></div>
Hi I posted a workaround of using owl owl.carousel#2.1.4 with angular 2.0.0 + webpack + jQuery#3.1.0.
Some of the issues I faced was with the jQuery plugin.
Please be more specific about the exception/error...
First U'll need to install the above^ packages via npm or similar.
Then --> npm install imports-loader
(for using owl within component otherwise u'll get fn is undefined...since third-party modules are relying on global variables like $ or this being the window object...).
In case you are using WebPack:
imports-loader as follow:
{test: /bootstrap\/dist\/js\/umd\//, loader: 'imports?jQuery=jquery'}
Also u can use jQuery with webpack:
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
In the plugin section of webpack.common.js:
plugins: [
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery'
})
]
For images loader:
{
test: /\.(png|jpe?g|gif|ico)$/,
loader: 'file?name=public/img/[name].[hash].[ext]'
}
*public/img -- images folder
CSS loader:
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
The vendors.js file should import the following:
import 'jquery';
import 'owl.carousel';
import 'owl.carousel/dist/assets/owl.carousel.min.css';
Please be aware that owl.carousel 2 is still use andSelf() deprecated function of jQuery so we need to replace them with the new version of addBack().
Goto node_modules folder in the owl package dist/owl.carousel.js:
replace all the occurrences of andSelf() with --> addBack().
Now is the angular 2 part:
owl-carousel.ts:
import {Component} from '#angular/core';
#Component({
selector: 'carousel',
templateUrl: 'carousel.component.html',
styleUrls: ['carousel.css']
})
export class Carousel {
images: Array<string> = new Array(10);
baseUrl: string = './../../../../public/img/650x350/';
}
carousel.component.ts:
import { Component, Input, ElementRef, AfterViewInit, OnDestroy } from '#angular/core';
#Component({
selector: 'owl-carousel',
template: `<ng-content></ng-content>`
})
export class OwlCarousel implements OnDestroy, AfterViewInit{
#Input() options: Object;
$owlElement: any;
defaultOptions: Object = {};
constructor(private el: ElementRef) {}
ngAfterViewInit() {
for (var key in this.options) {
this.defaultOptions[key] = this.options[key];
}
var temp :any;
temp = $(this.el.nativeElement);
this.$owlElement = temp.owlCarousel(this.defaultOptions);
}
ngOnDestroy() {
this.$owlElement.data('owlCarousel').destroy();
this.$owlElement = null;
}
}
carousel.component.html:
<owl-carousel class="owl-carousel"[options]="{navigation: true, pagination: true, rewindNav : true, items:2, autoplayHoverPause: true, URLhashListener:true}">
<div class="owl-stage" *ngFor="let img of images; let i=index">
<div class="owl-item">
<img src="{{baseUrl}}{{i+1}}.png"/>
</div>
</div>
</owl-carousel>
Make sure to bootstrap everything in the app.module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import {OwlCarousel} from './components/carousel/carousel.component';
import {Carousel} from './components/carousel/owl-carousel';
#NgModule({
imports: [
BrowserModule,
NgbModule,
],
declarations: [
AppComponent,
OwlCarousel,
Carousel
],
providers: [appRoutingProviders],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Categories