Error While Read Excel Data Using Angular - html

I have a code to read data from excel using Angular Typescript. Its working file till converted to JSON. But didn't fetch into HTML Page. Problem is in column name of Excelsheet.
Excel file column names are like (i) Autodesk Material Description (ii) Autodesk SAP Material Description
If I use in HTML {{pricedata.Autodesk Material Description}}, {{pricedata.Autodesk SAP Material Description}}. It gives me error.
So I converted that name into (i) Autodesk_Material_Description (ii) Autodesk_SAP_Material_Description IN EXCELSHEET and code too ({{pricedata.Autodesk_Material_Description}}, {{pricedata.Autodesk_SAP_Material_Description}}).
Now it's working fine. So, how to handle this problem ?
import { Component, HostListener } from '#angular/core';
import * as XLSX from 'xlsx';
#Component({
selector: 'app-importpricelist',
templateUrl: './importpricelist.component.html',
styleUrls: ['./importpricelist.component.css']
})
export class ImportpricelistComponent
{
ExcelData:any;
constructor(){
}
ReadExcel(event:any){
let file = event.target.files[0];
let fileReader = new FileReader();
fileReader.readAsBinaryString(file);
fileReader.onload = (e) => {
var workBook = XLSX.read(fileReader.result, {type:'binary'});
var SheetNames = workBook.SheetNames;
this.ExcelData = XLSX.utils.sheet_to_json(workBook.Sheets[SheetNames[0]]);
console.log(this.ExcelData);
}
}
}

Related

Angular catching a 404 file not found error while using ngx-doc-viewer

I have implemented ngx-doc-viewer to be able to render docx files in my webapp. Since the webapp is multilanguage, I do have different docx for every implemented language and I do load the correct docx, depending on the current language selected. Now I would like to handle the scenario where the docx file of a certain language is, for some reason, missing which will lead me to load a default docx file (let's say the english one). I think I need to somehow catch the response error I get in the console, when the component cannot find the target file, but I don't know how. Can you help me please? Thanks!!
Here's some of my code:
HTML:
<mat-dialog-content class="text">
<ngx-doc-viewer [url]="docUrl" [viewer]="viewer"></ngx-doc-viewer>
</mat-dialog-content>
TS:
import { Component, Inject, OnInit } from '#angular/core';
import { MAT_DIALOG_DATA } from '#angular/material/dialog';
import { viewerType } from 'ngx-doc-viewer';
#Component({
selector: 'app-privacy-text',
templateUrl: './privacy-text.component.html',
styleUrls: ['./privacy-text.component.scss']
})
export class PrivacyTextComponent implements OnInit {
docLanguage = navigator.language.split('-')[1].toString().toLocaleLowerCase();
viewer: viewerType; // google, office, mammoth, pdf, url
docUrl = '';
constructor(
#Inject(MAT_DIALOG_DATA) public data: {width: string, height: string}) { }
ngOnInit(): void {
this.viewer = 'mammoth';
this.docUrl = 'assets/docs/terms_and_conditions-' + this.docLanguage + ".docx";
}
}
CONSOLE error msg:
GET http://localhost:4200/assets/docs/terms_and_conditions-it.docx [HTTP/1.1 404 Not Found 5ms]
Response:
Cannot GET /assets/docs/terms_and_conditions-it.docx

Not uploading CSV file in vue.js

I have started with vue and D3. I just want to show my csv data in the console but when I try to do it with D3 CSV function is not working at all. Appears an array of 16 HTML elements which are in index.html, would you mind helping me with this?
This is my project structure:
This is my component code:
<template>
</template>
<script>
import * as d3 from "d3";
import { csv } from 'd3';
export default {
name: 'mycomponent',
data() {
return{
dataset: [],
}
},
async mounted(){
const data = await d3.csv('./datasets/dataset.csv')
this.$data.$dataset = Object.freeze(data)
console.log(data);
}
}
</script>
This is home:
<template>
<mycomponent></mycomponent>
</template>
<script>
import mycomponent from '#/components/mycomponent.vue'
export default {
name: 'Home',
components: {
mycomponent,
},
}
</script>
And this is what I get in console:
The d3.csv function will execute at runtime not compile-time so you have to put your csv file in public directory then use it as usual public files.
let data = await d3.csv("/datasets/dataset.csv")
Or if you want to load your csv file at compile-time you can import it as string and use d3.csvParse instead.
import dataset from '#/datasets/dataset.csv'
let data = d3.csvParse(dataset);
I would prefer the first method, in the second method your csv file might cause your script file too big.
Example

Angular 2 | Typescript | Mapping an string to a component name and return component

I got list of components that I would like to replace on certain conditions:
List of navigation components:
import {navigationDefaultComponent} from '';
import {navigationSmoothComponent} from '';
import {navigationMobileComponent} from '';
navigations: [
{component: navigationDefaultComponent},
{component: navigationSmoothComponent},
{component: navigationMobileComponent},
]
I have an object that comes from API and tel's me what component I should show
const X = {
name: 'John Smith',
navigation: 'navigationDefaultComponent'
}
I have done it this way, as I can't store the component in the api. The API can not return me a component. If there is a way please do let me know.
So my goal is is to have a const that will go through navigation object and based on x.navigation string will map and return me the component.
const nav = ????
Well, this is a typical situation.
You would need to make one of your component to listen to ** route and then use dynamic component loading. https://angular.io/guide/dynamic-component-loader
You can create an array having string and Component
let mapping = [
{'name':'name1', 'component':Component1},
{'name':'name2', 'component':Component2},
{'name':'name3', 'component':Component3},
{'name':'name4', 'component':Component4},
{'name':'name5', 'component':Component5},
];
Please Note that Component1, Component2 are direct reference to the Component and not their string representations.
Create a directive, to be included in your AppComponent
import { Directive, ViewContainerRef } from '#angular/core';
#Directive({
selector: '[app-directive]',
})
export class AppDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Include the directive in your template
<ng-template app-directive></ng-template>
Get the reference to your directive in ts file
#ViewChild(AppDirective) appDirective: AppDirective;
Now load the desired component after getting the response from the API
// let's assume name1 is what API returned
let component = this.mapping['name1'];
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(mapping[component);
let viewContainerRef = this.appDirective.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
I hope this solves your problem...

Load Script Tag in Angular 2 App When Src Attribute is from Web API Call

Context:
I have an Angular 2+ application that makes calls to a web API containing URLs for a src attribute on a script tag that is created by a loadScript function in the AfterViewInit lifecycle hook.
The web API returns a JsonResult and is yielding the data I expect. I was able to interpolate some of the data in the component's template.
Additionally, before I added the call to the web API, the loadScript function was working with a hard-coded argument.
Reading a thread on github. A "member" stated that scripts are not supposed to be loaded on demand. So what I implemented with the loadScript function is essentially a work around, but how else would load them? I don't want to have a seemingly endless amount of script tags sitting in the index.html file.
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Http } from '#angular/http';
#Component({
selector: 'app-agriculture-roadmap',
templateUrl: './agriculture-roadmap.component.html',
styleUrls: ['./agriculture-roadmap.component.css']
})
export class RoadmapComponent implements OnInit, AfterViewInit {
constructor(private _httpService: Http, private _route: ActivatedRoute)
{
}
apiRoadmaps: { roadmapName: string, pdfRoadmapURL: string, jsRoadmapURL: string };
ngOnInit() {
this._httpService
.get('/api/roadmaps/' + this._route.params)
.subscribe(values => {
this.apiRoadmaps = values.json() as { roadmapName: string, pdfRoadmapURL: string, jsRoadmapURL: string };
});
}
async ngAfterViewInit() {
await this.loadScript(this.apiRoadmaps.jsRoadmapURL);
}
private loadScript(scriptUrl: string) {
return new Promise((resolve, reject) => {
const scriptElement = document.createElement('script')
scriptElement.src = scriptUrl
scriptElement.onload = resolve
document.body.appendChild(scriptElement)
})
}
}
If you are using angular cli .
Then place these scripts in
angular-cli.json file under scripts array
scripts:[
.....
]
Please refer this [link] (https://rahulrsingh09.github.io/AngularConcepts/faq)
It has a question on how to refer third party js or scripts in Angular with or without typings.

Csv Reader Typescript

I'm trying to build a simple csv reader for our project. first i builded one in JS and it worked fine, but i have difficulties converting it to ts.
this is the simple html code:
<div id="dvImportSegments" class="fileupload">
<fieldset>
<legend>Upload your CSV File</legend>
<input type="file" name="File Upload" id="txtFileUpload" (change)="changeListener($event)" accept=".csv"/>
</fieldset>
</div>
and this is the typescript that run on it:
import {Component, ViewEncapsulation} from 'angular2/core';
import {Router} from 'angular2/router';
import {ContentService} from "../service/contentService";
import {RouteParams} from "angular2/router";
#Component({
selector: 'createCsv',
templateUrl: 'app/partials_html/createCsv.component.html',
encapsulation: ViewEncapsulation.None
})
export class CreateCsvComponent {
changeListener($event):void {
this.upload($event.target);
}
upload(inputValue:any):void {
var data = null;
var file:File = inputValue.files[0];
var reader:FileReader = new FileReader();
//reader.readAsText(file);
reader.onloadend = function (e) {
var csvData = reader.result;
data = $.csv.toArrays(csvData); //???
if (data && data.length > 0) {
alert('Imported -' + data.length + '- rows successfully!');
} else {
alert('No data to import!');
}
};
reader.onerror = function () {
alert('Unable to read ' + file);
};
}
//}
}
but i have some errors, data = $.csv.toArrays(csvData); //??? he cannot find the $ sign in there, how can i adress that?
Thanks in advance
he cannot find the $ sign in there
You are probably using https://github.com/evanplaice/jquery-csv
You need a TypeScript declaration file for JavaScript libraries that are not a part of your code base. A simple one vendor.d.ts:
declare var $:any;
Also you need to look at your module loader to make sure that the desired libraries are loaded before you code runs.
More
Some docs on declaration files and migrating : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html