I have crud app , which user can add comments , I want comments to be displayed under each section commented, now all added comments displays below all section.
here is components ts
import { Component, OnInit } from '#angular/core';
import { Task } from '../model/task.model';
import { Comment } from '../model/comment.model';
import { Router } from '#angular/router';
import { UserService } from '../service/user.service';
import {first} from 'rxjs/operators';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-task-list',
templateUrl: './task-list.component.html',
styleUrls: ['./task-list.component.scss']
})
export class TaskListComponent implements OnInit {
tasks: Task[];
comments: Comment[];
// tslint:disable-next-line:max-line-length
constructor(private formBuilder: FormBuilder, private router: Router, private activeRouter: ActivatedRoute, private userService: UserService) { }
addForm: FormGroup;
ngOnInit() {
this.userService.getTask()
.subscribe( data => {
this.tasks = data;
});
this.activeRouter.params.subscribe((params) => {
// tslint:disable-next-line:prefer-const
let id = params['id'];
this.userService.getComments(id)
.subscribe(data => {
this.comments = data;
});
});
this.addForm = this.formBuilder.group({
id: [],
author: ['', Validators.required],
description: ['', Validators.required],
});
}
addComments(task_id) {
const formData = this.addForm.value;
formData.task_id = task_id;
this.userService.addComments(formData)
.subscribe(data => {
this.comments.push(this.addForm.value);
});
this.router.navigate(['task-list']);
}
}
Here is task list html i have
<div class="container task-list">
<div class="row">
<div class="col-sm-8">
<div class="panel panel-white post panel-shadow" *ngFor="let task of tasks">
<div class="post-heading">
<div class="pull-left meta">
<div class="title h4">
<b>{{task.title}}</b>
</div>
<h6 class="text-muted time">1 minute ago</h6>
</div>
</div>
<div class="post-description">
<p>{{task.description}}</p>
<div class="stats">
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-up icon"></i>2
</a>
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-down icon"></i>12
</a>
</div>
</div>
<form class="post-form" [formGroup]="addForm" (ngSubmit)="addComments(task.id)">
<div class="form-group task-group">
<div class="form-group">
<label class="">Author</label>
<input type="text" class="form-control" formControlName="author" id="author" />
</div>
<div class="form-group">
<label class="">Comments</label>
<textarea class="form-control task-textarea" rows="1" formControlName="description" id="description" ></textarea>
</div>
</div>
<button class="btn btn-default btn-submit">Submit</button>
</form>
</div>
</div>
<div class="col-sm-8">
<div class="panel panel-white post panel-shadow" *ngFor="let comment of comments">
<div class="post-heading">
<div class="pull-left image">
<img src="http://bootdey.com/img/Content/user_1.jpg" class="img-circle avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
<b>{{comment.author}}</b>
made a post.
</div>
<h6 class="text-muted time">1 minute ago</h6>
</div>
</div>
<div class="post-description">
<p>{{comment.description}}</p>
<div class="stats">
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-up icon"></i>2
</a>
<a href="#" class="btn btn-default stat-item">
<i class="fa fa-thumbs-down icon"></i>12
</a>
</div>
</div>
</div>
</div>
</div>
</div>
Here is services for getting task and comments
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { User } from '../model/user.model';
import { Task } from '../model/task.model';
import { Comment } from '../model/comment.model';
#Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) { }
baseUrl = 'http://localhost:3000/users';
taskUrl = 'http://localhost:3000/task';
commentsUrl = 'http://localhost:3000/comment';
getUsers() {
return this.http.get<User[]>(this.baseUrl);
}
getUserById(id: number) {
return this.http.get<User>(this.baseUrl + '/' + id);
}
createUser(user: User) {
return this.http.post(this.baseUrl, user);
}
updateUser(user: User) {
return this.http.put(this.baseUrl + '/' + user.id, user);
}
deleteUser(id: number) {
return this.http.delete(this.baseUrl + '/' + id);
}
createTask(task: Task) {
return this.http.post(this.taskUrl, task);
}
getTask() {
return this.http.get<Task[]>(this.taskUrl);
}
addComments(comment: Comment) {
return this.http.post(this.commentsUrl, comment);
}
getComments(id: number) {
return this.http.get<Comment[]>(this.commentsUrl);
}
/*
getComments(id: number) {
return this.http.get<Comment[]>(this.commentsUrl + id);
}
*/
}
Problem: when I add comments in a certain task , displays beloww all task I have ,
Here is image how it look after adding comment
Here is what I want
What do I need to change in my code to get what I want? thanks
Related
I will appreciate any ideas and support for this issue
I have an angular project and I try to create icons share buttons for social media.
I have a component named landing.component. in the HTML file I implemented a Modal popup to allow showing a new windows where I have the icons. Please, follow screenshots below
Below, is the new windows
the HTML code is here
<div class="card-wrapper" fxLayout="row wrap" fxLayoutAlign="start start">
<div
class="card active-card"
fxFlex="25"
*ngFor="let category of categories"
(click)="categoryClick(category)"
>
<picture>
<img [src]="category.imageLocation" />
</picture>
<div class="card-overlay" fxLayout="row wrap" fxLayoutAlign="center end">
<span class="card-title" fxFlex="100">{{ category.title }}</span>
<div class="card-buttons" fxFlex="100" fxLayout="row">
<ul class="list-inline text-center member-icons ">
<li class="list-inline-item">
<button mat-icon-button disableRipple class="btn btn-primary" routerLink="/mtl" (click)="open(content)"><i class="fa-solid fa-share"></i></button>
</li>
<span fxFlex></span>
</ul>
<!-- <button mat-icon-button disableRipple>
<heart-icon></heart-icon>
</button> -->
<!-- <span fxFlex></span> -->
<!-- <button mat-icon-button disableRipple> -->
<!-- <download-icon></download-icon> -->
<!-- </button> -->
<!-- <button mat-icon-button disableRipple>
<share-icon></share-icon>
</button> -->
</div>
</div>
</div>
</div>
<section
class="cragcity-container p-t-5"
fxLayout="row"
fxLayoutAlign="space-between start"
>
<div style="margin: auto">
<img class="socmed-icon m-r-15" src="./assets/icons/facebook.webp" />
<img class="socmed-icon m-r-15" src="./assets/icons/skype.webp" />
<img class="socmed-icon" src="./assets/icons/instagram.webp" />
</div>
</section>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Share Social Media</h4>
<button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
</div>
<div class="modal-body">
<form>
<div class="mb-3">
<label for="Social Media"></label>
<div class="share-btn-container">
<a #facebook href="#" class="facebook-btn">
<i class="fab fa-facebook"></i>
</a>
<a href="#" class="twitter-btn">
<i class="fab fa-twitter"></i>
</a>
<a href="#" class="pinterest-btn">
<i class="fab fa-pinterest"></i>
</a>
<a href="#" class="linkedin-btn">
<i class="fab fa-linkedin"></i>
</a>
<a href="#" class="whatsapp-btn">
<i class="fab fa-whatsapp"></i>
</a>
</div>
<!-- <div class="input-group">
<input
name="dp"
ngbDatepicker
#dp="ngbDatepicker"
/>
<button class="btn btn-outline-secondary bi bi-calendar3" (click)="dp.toggle()" type="button"></button>
</div> -->
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Close</button>
</div>
</ng-template>
<app-cragcity-footer></app-cragcity-footer>
In the facebook option, I created a variable #facebook that will allow me to use viewchildren in the ts file to do an elementref and find the element in the DOM.
In the viewchildren option, I created a variable link1.
then, in the ngAfterViewInit I created two variables url and title. the url variable will take the link of my page to be share and the title is just message.
Finally, I used this command:
this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)
(this is what I believe is the same in js document.location.href) but used in ts
The code is not working, basically when I click the facebook icon only close the windows and that's it and the web shows me this error here bbelwo:
the landing. component.ts code is here below:
import { Component, OnInit, Input, ViewChild, ElementRef, AfterViewInit, ViewChildren } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { DataService } from 'src/app/core/services/data.service';
import { category } from '../models/category';
import { ModalDismissReasons, NgbActiveModal, NgbModal } from '#ng-bootstrap/ng-bootstrap';
#Component({
selector: 'app-landing',
templateUrl: './landing.component.html',
styleUrls: ['./landing.component.scss']
})
export class LandingComponent implements OnInit, AfterViewInit {
public categories = new Array<category>();
#Input() name;
url:string;
title:string;
closeResult: string | undefined;
constructor(private _dataService: DataService, private router: Router, private modalService: NgbModal, private route: ActivatedRoute) {
}
ngOnInit(): void {
this.retrieveCategories();
}
#ViewChildren("facebook")link1: ElementRef;
ngAfterViewInit() {
this.url = this.router.url;
/* this.link1.nativeElement = this.url; */
this.title = encodeURI("Facebook");
this.link1.nativeElement.setAttribute("href",`https://www.facebook.com/sharer.php?u=${this.url}`)
/* console.log(this.link1);
console.log(this.url);
*/
/* this.link1.nativeElement.setAttribute('xlink:href') */
}
retrieveCategories() {
const actionUrl = 'v1/category';
const params = {};
this._dataService.get<any>(actionUrl, params)
.subscribe(data => {
if (data !== null) {
if (!data.isError) { this.categories = data.result; }
}
});
}
categoryClick(data: category) {
if (data.subCategory.length > 0)
this.router.navigate(['mtl', data.id]);
}
open(content) {
this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then(
(result) => {
this.closeResult = `Closed with: ${result}`;
},
(reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
},
);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
I really appreciate any help
Regards
First it is a different between #ViewChild and #ViewChildren. The first will search one element, the second multiple elements. So in your case use #ViewChild("facebook") link1: any;
But a besser approach is to let Angular do this thing and don't use setAttribute to the native element. So you can bind anything to the href attribute like this:
HTML
<a #facebook [href]="facebookLink" class="facebook-btn">
<i class="fab fa-facebook"></i>
</a>
Code
facebookLink: string = "https://facebook.com";
You can generate the links with a ngFor loop, too for more flexibility.
CODE
linkObjects = [{iconClassI: "fab fa-facebook", iconClassA: "facebook-btn", link: "http://facebook.com"}, {... all other links}]
HTML
<div class="share-btn-container">
<a *ngFor="let item of linkObjects" [href]="item.link" [class]="item.iconClassA">
<i [class]="item.iconClassI"></i>
</a>
</div>
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}}
In Angular i have dynamically created a group of buttons that all have the same action (to show text when clicked) everything works fine yet when I click one button they all perform the action. I need them to work independently of each other. I have dynamically made a different id for each button and was wondering if there was a way to us the id to have them work independently.
Button HTML and TS files:
<button id="{{index}}" class="btn btn-secondary" style="float: right;" (click)="onClick()">Discription</button>
import { Component, EventEmitter, OnInit, Output, Input } from '#angular/core';
#Component({
selector: 'app-discription-btn',
templateUrl: './discription-btn.component.html',
styleUrls: ['./discription-btn.component.css']
})
export class DiscriptionBtnComponent implements OnInit {
#Output() btnClick = new EventEmitter();
#Input() index!: number
constructor() { }
ngOnInit(): void { }
onClick() {
this.btnClick.emit();
}
}
Button Parent HTML and TS files:
<div class="card mb-4 h-100">
<img class="card-img-top-other" src= "{{ post.link }}" />
<div class="card-body">
<div class="small text-muted"> {{ post.created }} <app-discription-btn (btnClick) = "toggleDiscription()" [index] = index></app-discription-btn> </div>
<h2 class="card-title h4"> {{ post.title }} </h2>
<div *ngIf="showDiscription">
<p class="card-text"> {{ post.summary }} </p>
<a class="btn btn-primary" href="#!">Read More -></a>
</div>
</div>
</div>
import { Component, OnInit, Input } from '#angular/core';
import { Subscription } from 'rxjs';
import { BlogPost } from 'src/app/Post';
import { DiscriptionUiService } from 'src/app/services/discription-ui.service';
#Component({
selector: 'app-other-posts',
templateUrl: './other-posts.component.html',
styleUrls: ['./other-posts.component.css']
})
export class OtherPostsComponent implements OnInit {
#Input() post! : BlogPost
#Input() index! : number;
showDiscription : boolean = false;
subscription : Subscription;
constructor(private discritpionService: DiscriptionUiService) {
this.subscription = this.discritpionService.onToggle().subscribe((value) => (this.showDiscription = value));
}
ngOnInit(): void {
}
toggleDiscription(){
this.discritpionService.toggleDiscription();
}
}
Main HTML and TS files:
<div class="container">
<div class="row">
<div class="col-lg-8"><app-featured-post *ngFor="let post of posts; let i = index;" [post] = "post" [index] = "i"></app-featured-post></div>
<div class="col-lg-4"><app-side-widgets></app-side-widgets></div>
<app-other-posts *ngFor="let post of posts | myFilterPipe:filterargs; let i = index;" [post] = "post" [index] = "i" class="col-lg-4" style="padding-top: 10px;" ></app-other-posts>
<nav aria-label="Pagination">
<hr class="my-0" />
<ul class="pagination justify-content-center my-4">
<li class="page-item disabled"><a class="page-link" href="#" tabindex="-1" aria-disabled="true">Newer</a></li>
<li class="page-item active" aria-current="page"><a class="page-link" href="#!">1</a></li>
<li class="page-item"><a class="page-link" href="#!">Older</a></li>
</ul>
</nav>
</div>
</div>
import { Component, OnInit } from '#angular/core';
import { BlogPostService } from 'src/app/services/blog-post.service';
import { BlogPost } from '../../Post';
#Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
filterargs = {title: 'The Beginning'}
posts: BlogPost[] = [];
constructor(private postService: BlogPostService ) { }
ngOnInit(): void {
this.postService.getPosts().subscribe((posts) => (this.posts = posts));
}
}
Any ideas would be a great help. Thank you ahead of time!
I am using js-year-calendar plugin to display all the months in a year at once. However, i can select just one day at a time and then store the date in the database. Please, is there a way to select multiple days e.g. 2020/08/04 - 2020-08-12 and then store this range in the database at once. Meanwhile, i have gone through the documentation but its was not clear to me. Please i need assistance to get a clear picture on how to go about this. Thanks
This is my view. I am sorry for the long code, i really assistance
HTML
<section id="filter" class="mb-3">
<div class="card">
<div class="col-sm-12">
<div class="card-header mt-3">
<div class="card-title-wrap bar-info">
<h4 class="card-title ml-4">{{'ALL_COMPANIES_HOLIDAY_CALENDER' | translate}}</h4>
</div>
</div>
<div class="card-body">
<div class="card-block">
<div class="row">
<div class="col-md-6 col-lg-6">
<div class="row">
<div class="col-md-4 col-lg-4 col-12 mt-1 ml-4">
<div class="form-group row">
<div class="col-md-12 searchcat">
<select class="form-control " [(ngModel)]="holidays.company_id" id="company" name="company" (change)="getSelectedCompany(holidays.company_id)" required>
<option value="" disabled selected hidden>{{'SELECT_COMPANY' | translate}}</option>
<option *ngFor="let data of companyList; let i = index" [value]="data.id" >{{data.company_name}}</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-5 ml-2">
<div class="col-md-12 col-lg-12">
<div id="calendar">
</div>
</div>
</div>
<div class="card-body">
<div class="card-block">
<div class="clearfix"></div>
<ngx-datatable #table class='bootstrap' [columnMode]="'force'" [headerHeight]="50" [footerHeight]="50"
[rowHeight]="'auto'" [limit]="50" [rows]='holidaysDataRows'>
<ngx-datatable-column name="{{'COMPANY_NAME' | translate}}" prop="company_name"></ngx-datatable-column>
<ngx-datatable-column name="{{'YEAR' | translate}}" prop="year"></ngx-datatable-column>
<ngx-datatable-column name="{{'HOLIDAY' | translate}}" prop="holidays_date">
</ngx-datatable-column>
<ngx-datatable-column name="{{'DESCRIPTION' | translate}}" prop="description" > </ngx-datatable-column>
<ngx-datatable-column name="{{'ACTIONS' | translate}}" prop="status">
<ng-template ngx-datatable-cell-template let-rowIndex="rowIndex" let-value="value" let-row="row"
let-group="group" let-rowHeight="rowHeight">
<button (click)="editHoliday(editModal,row)" class="btn btn-raised mr-1 shadow-z-2 btn-info btn-sm ">{{'EDIT' | translate}}</button>
<button (click)="deleteModal(deleteholiday, row.holiday_id)" class="btn btn-raised mr-1 shadow-z-2 btn-danger btn-sm ">{{'DELETE' | translate}}</button>
</ng-template>
</ngx-datatable-column>
</ngx-datatable>
<div class="loader-div" *ngIf="showLoader">
<img src="assets/img/portrait/small/loader.gif" alt="spinner" class="loader">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
TS CODE
import { Component, OnInit, ViewChild } from '#angular/core';
import { SnotifyService } from 'ng-snotify';
import { Router, ActivatedRoute } from "#angular/router";
import { NgbModal, ModalDismissReasons, NgbActiveModal } from '#ng-bootstrap/ng-bootstrap';
import { HumanResourceService } from 'app/services/human-resource/human-resource.service';
import { TranslateService } from '#ngx-translate/core';
import { AuthenticationService } from 'app/services/authentication/authentication.service';
import { HumanResourceMasterService } from '../../../services/human-resource-master/human-resource-master.service';
import Calendar from 'js-year-calendar';
import * as moment from 'moment';
import { GlobalConstants } from 'app/shared/constants/global-constants';
#Component({
selector: 'app-all-company-holiday-calender',
templateUrl: './all-company-holiday-calender.component.html',
styleUrls: ['./all-company-holiday-calender.component.scss']
})
export class AllCompanyHolidayCalenderComponent implements OnInit {
#ViewChild('openModal') OpenModalotdeletepos;
companyList: any = [];
company_id: any = '';
datas: any;
dateFromModal : any;
closeResult: any;
currentHolidays: any = [];
holidaysDataRows: [];
HolidayDeleteData: any;
showLoader: boolean;
deleterowid: any;
holidaysData : any = [];
holidays: any = {
description: '',
date: '',
company_id:'',
hr_id: '',
hols_id: '',
}
selectedDate:any;
hrID: any;
eventDate: Date;
eventText: string;
myEvents: any[] = [];
constructor(private snotifyService: SnotifyService,private spinner:
FullLayoutComponent, private
route: ActivatedRoute, private modalService: NgbModal, private
loginService: LoginService,private hrMasterService:
HumanResourceMasterService, private hrService:
HumanResourceService, public authService: AuthenticationService,public
translate: TranslateService) {
ngOnInit() {
this.getDate();
}
getDate(){
var modalService = this.modalService;
var snotifyService = this.snotifyService;
var openModal = this.OpenModalotdeletepos;
var getDismiss = this.getDismissReason;
new Calendar('#calendar');
var holiday = this.holidays;
var translate = this.translate;
document.querySelector('#calendar').addEventListener('clickDay',
function(data) {
var hols = moment(data['date']).format(GlobalConstants.DATE_FORMAT);;
holiday.date = hols;
if(!holiday.company_id){
snotifyService.error(translate.instant('MESSAGE_PLEASE_SELECT_COMPANY'));
}
else{
modalService.open(openModal).result.then((result) => {
this.closeResult = GlobalConstants.CLOSE + `${result}`;
}, (reason) => {
this.closeResult = GlobalConstants.DISMISSED +
`${getDismiss(reason)}`;
});
}
})
}
getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return GlobalConstants.PRESS_ESC;
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return GlobalConstants.BACKDROP_CLICK;
} else {
return GlobalConstants.WITH + ` ${reason}`;
}
}
getHolidayData(){
this.showLoader = true;
this.hrMasterService.getHolidayData({}).subscribe(data => {
if(data.status_code = 200){
this.showLoader = false;
this.holidaysData = data.data;
this.holidaysDataRows = this.holidaysData;
}
else {
this.showLoader = false;
this.snotifyService.error(data.message);
}
})
}
saveHolidays(){
this.holidays.hr_id = this.hrID.id;
this.hrMasterService.createHolidays(this.holidays).subscribe(data =>{
if(data.status_code = 200){
this.snotifyService.success(this.translate.instant('MESSAGE_HOLIDAY_CREATED'));
this.modalService.dismissAll();
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
this.snotifyService.error(data.message);
}
},error=>{
});
}
onChangeDate(holiday){
}
getSelectedCompany(company_id: any){
}
}
Replace new Calendar('#calendar') with new Calendar('#calendar',{enableRangeSelection: true});
then you can get it here:
document.querySelector('#calendar').addEventListener('selectRange', function(e) {
console.log("Select the range: " + e.startDate + " - " + e.endDate);
})
Year Calendar Documentaion
Here is a Stackblitz
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!