Remove the file extension of each file angular 6 - javascript

The HTML is written where I am getting the file name but i want to get rid of the file extension and also store the files in an array and access them in the UI.
<div class="myReadingListContainer">
<div class="readingList">
My Reading List
</div>
<div class="myReadingList">
<div class="uploadWrap">
<input type="file" #file (change)="onChange(file.files)" class="fileUploadInput" />
<div class="innerText">
<img src="assets/img/my_reading_list/Add.svg" class="addIcon">
<h6 class="addFile">Add Files</h6>
</div>
</div>
<div *ngFor="let file of fileList">
<div class="selectedFile">
<div class="documentName">
{{file.name}}
</div>
<span *ngIf="file.type === 'application/pdf'">
<img src="assets/img/my_reading_list/PDF.svg" class="fileTypeImage">
</span>
<span *ngIf="file.type === 'application/vnd.ms-excel'">
<img src="assets/img/my_reading_list/Excel.svg" class="fileTypeImage">
</span>
<div class="readingStatus">
20/35 Pages
</div>
<div class="progress">
<div class="progressBar"></div>
</div>
</div>
</div>
</div>
</div>
The typescript file is written like this. Since I am new to Angular 6 any help is really appreciated, thanks in advance
import { Component, OnInit } from "#angular/core";
#Component({
selector: "app-myReadingList",
templateUrl: "./myReadingList.component.html",
styleUrls: \["./myReadingList.component.scss"\]
})
export class MyReadingListComponent implements OnInit {
//localUrl: String;
fileList: any = \[\];
files: any;
constructor() {}
onChange(files: FileList) {
console.log(files);
this.files = files;
this.fileList.push(files\[0\]);
this.fileList.forEach(file => {
let temp = file.name.split(".");
file.name = temp.splice(0, temp.length - 1).join(".");
});
console.log(this.fileList);
}
ngOnInit() {}
}

Here is the sample code to remove file extension while displaying from each fileList.name
<div class="documentName">
{{file.name.split('.').slice(0, -1).join('.')}}
</div>
Demo for the same

Related

I am working on exam portal using angular and spring boot, I got a problem here when i am using name as [name]

Component.html
<div class="bootstrap-wrapper" *ngIf="!isSubmit">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<!-- instructions -->
<h2>Instructions</h2>
</div>
<div class="col-md-8">
<!-- questions -->
<ng-container *ngIf="questions">
<h2>{{questions[0].quiz.title}}</h2>
</ng-container>
<mat-card *ngFor="let q of questions, let i= index" class="mt20">
<mat-card-content>
<p> Q {{i+1}}) <span [innerHTML]="q.content"></span> </p>
<mat-divider></mat-divider>
<div class="row mt20" >
<div class="col-md-6">
<input type="radio" [value]="q.option1"
[name]="i"
// this is where i am getting error
[(ngModel)] ="q.givenAnswer"
/>
{{q.option1}}
{{i}}
</div>
<div class="col-md-6">
<input type="radio" [value]="q.option2"
[name]="i"
// this is where i am getting error
[(ngModel)] ="q.givenAnswer"
/>
{{q.option2}}
{{i}}
</div>
</div>
<div class="row mt20">
<div class="col-md-6">
<input type="radio" [value]="q.option3"
// this is where i am getting error
[name]="i"
[(ngModel)] ="q.givenAnswer"
/>
{{q.option3}}
{{i}}
</div>
<div class="col-md-6">
<input
type="radio"
[value]="q.option4"
// this is where i am getting error
[name]="i"
[(ngModel)] ="q.givenAnswer"
/>
{{q.option4}}
{{i}}
</div>
</div>
</mat-card-content>
</mat-card>
<div class="container text-center mt20">
<button (click)="submitQuiz()" mat-raised-button color="accent">Submit
Quiz</button>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
<!-- Show Result -->
<div class="bootstrap-wrapper" *ngIf="isSubmit">
<div class="row">
<div class="col-md-6 offset-md-3">
<mat-card>
<mat-card-header>
<mat-card-title>
<h1 class="text-center mall">Quiz Result</h1>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<h1>Marks Obtained: {{marksGot}}</h1>
<h1>Correct Ansers: {{correctAnswers}}</h1>
<h1>Questions Attempted: {{attempted}}</h1>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="accent">Print</button>
<button mat-raised-button color="accent" [routerLink]="'/user-
dashboard/0'">Home</button>
</mat-card-actions>
</mat-card>
</div>
</div>
</div>
Component.ts
import { LocationStrategy } from '#angular/common';
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { QuestionService } from 'src/app/services/question.service';
import Swal from 'sweetalert2';
#Component({
selector: 'app-start-quiz',
templateUrl: './start-quiz.component.html',
styleUrls: ['./start-quiz.component.css']
})
export class StartQuizComponent implements OnInit {
qid;
questions;
marksGot = 0;
correctAnswers = 0;
attempted = 0;
isSubmit = false;
constructor(private locationSt: LocationStrategy, private _route: ActivatedRoute, private
_question: QuestionService) { }
ngOnInit(): void {
this.preventBackButton();
this.qid = this._route.snapshot.params['qid'];
this.loadQuestions();
}
loadQuestions() {
this._question.getQuestionsOfQuizForTest(this.qid).subscribe(
(data: any) => {
this.questions = data;
this.questions.forEach((q) => {
q['givenAnswer'] = '';
});
console.log(data);
},
(error) => {
Swal.fire('Error', 'Error in loading questions of quiz', 'error');
}
);
}
preventBackButton() {
history.pushState(null, null, location.href);
this.locationSt.onPopState(() => {
history.pushState(null, null, location.href);
})
}
submitQuiz() {
Swal.fire({
title: 'Do you want to Submit quiz?',
showCancelButton: true,
confirmButtonText: 'Submit Quiz',
icon: 'info',
}).then((e) => {
if (e.isConfirmed) {
//calculation
this.isSubmit=true;
this.questions.forEach((q) => {
if (q.givenAnswer == q.answer) {
this.correctAnswers++;
let marksSingle = this.questions[0].quiz.maxMarks / this.questions.length;
this.marksGot += marksSingle;
}
if (q.givenAnswer.trim() != '') {
this.attempted++;
}
});
console.log("Correct Answers " + this.correctAnswers);
}
})
}
}
enter image description here
When i am name as [name] it is showing number is not assignable to type String and when i am using name it is compiling successfully but i have three questions in a quiz and while selecting an option of a particular question other options of other questions are getting deselected. what to do?
Thanks in Advance
[(ngModel)]="q.givenAnswer" type="radio" [value]="q.option1" name={{i}}

Show Only One Value In Dropdown If There are Duplicates

Hi i'm trying to get the information of printers by the location. so if i have few printers at the same location ill see them both at the dropdown but i actually want to see only one location on the dropdown if they are the same location.
i know i can solve this in the database level and add relationships but maybe there is a way to do it without it ?
import {
Component,
OnInit
} from '#angular/core';
import {
HttpClient
} from '#angular/common/http';
import {
DomSanitizer
} from '#angular/platform-browser';
import {
Values
} from '../Models/Values';
#Component({
selector: 'app-value',
templateUrl: './value.component.html',
styleUrls: ['./value.component.css']
})
export class ValueComponent implements OnInit {
selectedPrinter: Values;
values: any;
constructor(private http: HttpClient, public sanitizer: DomSanitizer) {}
ngOnInit() {
this.getValues();
}
getValues() {
this.http.get('http://localhost:5000/api/values/').subscribe(response => {
this.values = response;
}, error => {
console.log(error);
})
}
}
<H2>Printer Manager</H2>
<div id="selectCompanyDiv">
<div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
<label for="">Select Location</label>
<select class="form-control" [(ngModel)]="selectedPrinter">
<option *ngFor="let each of values " [ngValue]="each.location">{{each.location}} </option>
<!-- {{each.specificLocation}} -->
</select>
<!-- Search -->
<!-- <input id="test" *ngFor="let each of values " class="form-control" type="search" placeholder="Search" {{values.location}}>
<button ondblclick="Access()">click here
</button> -->
</div>
<br>
<br>
<div>
<div *ngFor="let value of values" id="mainDiv">
<div *ngIf="value.location===selectedPrinter">
<span>HostName: {{value.hostName}}</span>
<br>
<!-- <span>Location: {{value.location}}</span> -->
<span>Manufacturer: {{value.manufacturer}}</span>
<br>
<span>IP: {{value.ip}}</span>
<br>
<h2>{{value.location}}</h2>
<span>{{value.specificLocation}}</span>
<br>
<a target="_blank" [href]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')">Full view</a>
<div>
<div *ngIf="value.model==='J480'" class="outerFrame">
<iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrotherj480" scrolling="no"></iframe>
</div>
<div *ngIf="value.model==='6530DW'" class="outerFrame">
<iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
</div>
</div>
</div>
</div>
getValues() {
this.http.get('http://localhost:5000/api/values/').subscribe(response => {
this.values = [...new Set(response)];
}, error => {
console.log(error);
})
}
What i would do is the following:
In getValues():
getValues() {
this.http.get('http://localhost:5000/api/values/').subscribe(response => {
this.values = Array.from(new Set(response));
}, error => {
console.log(error);
})
}
Take a look at Array.from documentation and Array.from(set)
Good luck!

Adding first page and last page on ngx-pagination - angular 9

I am using the ngx-pagination library for my angular app.
Besides the previous and next button I want to add 2 more buttons to go directly on the last page or on the first page.
How can I achieve this ?
Template logic
import { Component, OnInit } from '#angular/core';
import { TestimonialsDataService } from '../../services/testimonials-data.service';
#Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.scss']
})
export class CardComponent implements OnInit {
public authors: Object = {};
public pageList: number = 1;
constructor(private _testimonialsService: TestimonialsDataService) { }
ngOnInit(): void {
this._testimonialsService.getData().subscribe(data => this.authors = data);
}
}
<div class="container">
<div class="content">
<div class="card" *ngFor="let author of authors['user'] | paginate: {id: 'list-pagination', itemsPerPage: 9, currentPage: pageList}" >
<div class="card-content">
<img class="image" src="{{author.image}}"/>
<p class="author">{{author.name}}</p>
<p class="job">{{author.job}}</p>
<p class="company">{{author.company}}</p>
<p class="country"><span class="flag flag-IT"></span><span class="country">{{author.country}}</span></p>
</div>
</div>
</div>
<pagination-controls id="list-pagination" lastLabel="Next" class="list-pagination" directionLinks="true" (pageChange)="pageList = $event"></pagination-controls>
</div>
You can customize the pagination-template and try adding these buttons
<pagination-template #p="paginationApi" [id]="config.id
(pageChange)="config.currentPage = $event">
<div class="custom-pagination">
<div class="pagination-first-page">
<span (click)="p.setCurrent(1)">
First Page
</span>
</div>
<div class="pagination-previous" [class.disabled]="p.isFirstPage()">
<span *ngIf="!p.isFirstPage()" (click)="p.previous()">
<
</span>
</div>
<div class="page-number" *ngFor="let page of p.pages" [class.current]="p.getCurrent() === page.value">
<span (click)="p.setCurrent(page.value)" *ngIf="p.getCurrent() !== page.value">{{ page.label }}</span>
<div *ngIf="p.getCurrent() === page.value">
<span>{{ page.label }}</span>
</div>
</div>
<div class="pagination-next" [class.disabled]="p.isLastPage()">
<span *ngIf="!p.isLastPage()" (click)="p.next()"> > </span>
</div>
<div class="pagination-last-page">
<span (click)="p.setCurrent(p.getLastPage())">
Last Page
</span>
</div>
</div>
</pagination-template>

classList.toggle() not working IE11 Angular 7 (Invalid Calling Object)

I've just been testing my app on IE11 and I cant figure out why this isn't working,
I have this code it has three elements .hamburger-small, .hamburger-big and .menu
<div [class.shown]="!chatbarFullscreen">
<div [class.disabled]="router.url.includes('home')">
<img (click)="closeChatbar(true, router.url.includes('home') ? true : false)" *ngIf="chatbarFullscreen" src="../assets/images/whole-app/arrow-right.svg" alt="Arrow Right">
<img (click)="closeChatbar(false, router.url.includes('home') ? true : false)" *ngIf="!chatbarFullscreen" src="../assets/images/whole-app/arrow-left.svg" alt="Arrow Left">
</div>
<img (click)="goHome()" src="../assets/images/chatbar/header-logo.svg" alt="header logo">
<div id="small" (click)="hamburgerClick()" class="hamburger hamburger--slider hamburger-small">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</div>
</div>
<div id="big" (click)="hamburgerClick()" class="hamburger hamburger--slider hamburger-big">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</div>
<div class="menu">
<p (click)="closeChatbar(false); hamburgerClick();" [routerLink]="['/app/main/home']">Home</p>
</div>
</div>
and when you click it, it calls this function
hamburgerClick() {
const small = <HTMLElement>document.querySelector('.hamburger-small');
const big = <HTMLElement>document.querySelector('.hamburger-big');
const menu = <HTMLElement>document.querySelector('.menu');
small.classList.toggle('is-active');
big.classList.toggle('is-active');
menu.classList.toggle('show');
}
now It works on every other browser, Chrome, Firefox, Safari and Edge but not in IE I've seen similar questions but it seems as if it should work? I'm also getting this error in the console when I click the button for the first time, but it does not happen any other time
any help would be great..
EDIT
I have tried using #ViewChild() but it still isn't working, however the Invalid Calling Object error is no longer happening
#ViewChild('hamburgerBig') hamburgerBig: ElementRef;
#ViewChild('hamburgerSmall') hamburgerSmall: ElementRef;
#ViewChild('menu') menu: ElementRef;
hamburgerClick() {
this.hamburgerBig.nativeElement.classList.toggle('is-active');
this.hamburgerSmall.nativeElement.classList.toggle('is-active');
this.menu.nativeElement.classList.toggle('show');
}
Thanks!!
try using Renderer2 to manipulate dom elements along with ElementRef and ViewChild as other previously mentioned.
first import ViewChild, ElementRef and Renderer2
import { Renderer2, ElementRef, ViewChild } from '#angular/core';
get the Element using ViewChild of type ElementRef after you've made template references in your DOM, like
<div #hamburgerBig></div>
<div #hamburgerSmall></div>
<div #menu></div>
#ViewChild('hamburgerBig') hamburgerBig: ElementRef;
#ViewChild('hamburgerSmall') hamburgerSmall: ElementRef;
#ViewChild('menu') menu: ElementRef;
and do your stuff with your hamburgerClick function
hamburgerClick() {
const hamBigIsActive = this.hamburgerBig.nativeElement.classList.contains('is-active');
const hamSmallIsActive = this.hamburgerSmall.nativeElement.classList.contains('is-active');
const menuShow = this.menu.nativeElement.classList.contains('show');
if(hamBigIsActive) {
this.renderer.removeClass(this.hamburgerBig.nativeElement, 'is-active');
} else {
this.renderer.addClass(this.hamburgerBig.nativeElement, 'is-active');
}
if(hamSmallIsActive) {
this.renderer.removeClass(this.hamburgerSmall.nativeElement, 'is-active');
} else {
this.renderer.addClass(this.hamburgerSmall.nativeElement, 'is-active');
}
if(hamSmallIsActive) {
this.renderer.removeClass(this.menu.nativeElement, 'show');
} else {
this.renderer.addClass(this.menu.nativeElement, 'show');
}
}
or you could just simply use [ngClass](not sure why you aren't using this instead)
hope this helps
also dont forget to add render to your contructor
contructor(private renderer: Renderer2){}
Edit: here's the [ngClass] implementation
<div id="small"
(click)="hamburgerClick()"
[ngClass] = "{'is-active' : hamClick}"
class="hamburger hamburger--
slider hamburger-small">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</div>
<div id="big"
(click)="hamburgerClick()"
[ngClass] = "{'is-active' : hamClick}"
class="hamburger hamburger--slider
hamburger-big">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</div>
<div
[ngClass] = "{'show' : hamClick}"
class="menu">
<p (click)="closeChatbar(false); hamburgerClick();" [routerLink]="
['/app/main/home']">Home</p>
</div>
and then just use a function to switch
hamClick: boolean
hamburgerClick(){
this.hamClick = !this.hamClick;
}
there you go
Try to make a test with code below may help you to solve your issue.
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public show:boolean = false;
public buttonName:any = 'Show';
ngOnInit () { }
toggle() {
this.show = !this.show;
// CHANGE THE NAME OF THE BUTTON.
if(this.show)
this.buttonName = "Hide";
else
this.buttonName = "Show";
}
}
.is-active{color:green;
}
<button (click)="toggle()" id="bt">
Hide
</button>
<ng-container *ngIf="show">
<div style="margin: 0 auto;text-align: left;">
<div>
<label>Name:</label>
<div><input id="tbname" name="yourname" /></div>
</div>
<div>
<label>Email Address:</label>
<div><input name="email" id="email" /></div></div>
<div>
<label>Additional Information (optional):</label>
<div><textarea rows="5" cols="46"></textarea></div>
</div>
</div>
</ng-container>
Further, You can try to modify the code based on your requirement.

angular4 viewchild not working on dom element

i want to know how to fetch the dom element from a components template :
Component
export class JokeListComponent implements OnInit, AfterViewInit {
jokes: Joke[];
constructor() { }
#ViewChild('.myclass') el: ElementRef;
ngOnInit() {
this.jokes = [
new Joke('joke1', 'content1'),
new Joke('Joke2', 'content2'),
new Joke(),
];
}
ngAfterViewInit(): void {
console.log(this.el);
}
}
View
<div class="card">
<div class="card-block">
<h4 class="card-title"> New Joke Form </h4>
<div class="myclass">
</div>
<div class="form-group">
<label for="jokeHeader">Joke Header</label>
<input type="text" id="jokeHeader" class="form-control" placeholder="Joke Head" #jokeHead>
</div>
<div class="form-group">
<label for="jokeContent">Joke Header</label>
<input type="text" id="jokeContent" class="form-control" placeholder="Joke Content" #jokeContent>
</div>
<button class="btn btn-primary" (click)="addJoke(jokeHead.value, jokeContent.value)"> Validate </button>
</div>
</div>
<hr>
<joke *ngFor="let joke of jokes" [joke]="joke" (deleteEvt)="deleteJoke($event)"></joke>
the problem is that this.el is always undefined, i dont know why.
PS: i'm using the last version of angular 4
You cannot use the class name for the #ViewChild, you will need a local variable:
#Component({
template: `
<div><span #myVar>xxx</span><div>`
})
class MyComponent {
#ViewChild('myVar') myVar:ElementRef;
ngAfterViewInit() {
console.log(this.myVar.nativeElement);
}
}

Categories

Resources