I have added particles.js to an Angular 4 project like mentioned here
Json file is being loaded but I don't see particles on screen
In .ts component :
import { Component, Output, ViewEncapsulation, OnInit } from '#angular/core';
import { MnFullpageOptions, MnFullpageService } from 'ngx-fullpage';
declare var particlesJS: any;
#Component({
selector: 'app-root',
encapsulation: ViewEncapsulation.None,
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
#Output() public options: MnFullpageOptions = new MnFullpageOptions({
autoScrolling: true,
controlArrows: false,
});
ngOnInit() {
particlesJS.load('particles-js', 'assets/particlesjs-config.json', console.log('callback - particles.js config loaded'));
}
constructor() { }
}
Html file :
<div id="particles-js" style="border:2px solid black; background-color:red">
<div class="menu-wrapper">
</div>
<div id="content-wrapper" [mnFullpage]="options" [mnFullpageNavigation]="true" [mnFullpageKeyboardScrolling]="true" [mnFullpageSlidesNavigation]="true" mnFullpageSlidesNavPosition="bottom">
<div class="section welcome-section fp-section fp-table ">
<div class="fp-tableCell ">
<div id="presentation" class="example-card" fxLayout="row">
<app-slide-presentation>
</app-slide-presentation>
</div>
</div>
</div>
<div class="section welcome-section fp-section fp-table">
<div class="fp-tableCell">
<div id="formation" class="example-card" fxLayout="row" fxLayoutAlign="center center">
<app-formation>
</app-formation>
</div>
</div>
</div>
<div class="section welcome-section fp-section fp-table">
<div fxLayout="row" class="fp-tableCell " style="height:100%; width:60%; overflow:hidden; margin:auto ; background-color:white ">
<div class="slide" >
<app-competences1>
</app-competences1>
<div class="slide" style="background-color:white">
>
</div>
<div class="slide">
</div>
<div class="slide">
</div>
<div class="slide">
</div>
</div>
</div>
</div>
</div>
</div>
In console I get callback message :
callback - particles.js config loaded
I have initiated a new project where everything is being working :
in ts component file :
import { Component, Input, Output, OnInit, ViewEncapsulation } from '#angular/core';
declare var particlesJS: any;
#Component({
selector: 'app-root',
encapsulation: ViewEncapsulation.None,
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
ngOnInit() {
particlesJS.load('particles-js', 'assets/particlesjs-config.json', null);
}
}
in html :
<div id="particles-js"></div>
particles are loading perfectly.
I don't see the difference between 2 examples.
Adding "background-color" to 'particles-js' container worked for me.
#home.component.html:
<div id="particles-js"></div>
#home.component.scss:
#particles-js {
height: 100vh;
background-color: black;
}
Related
I am working on an e-commerce app who's front-end is made in Angular 13.
The UI has a sidebar which I do not want to display on the product details page.
For this purpose, in app\app.component.ts I have:
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'E-commerce';
constructor(private router: Router) {}
ngOnInit() {}
/**
* Check if the router url contains the specified route
*
* #param {string} route
* #returns
* #memberof AppComponent
*/
hasRoute(route: string) {
return this.router.url.includes(route);
}
}
In app\app.component.html:
<div class="app-wrapper">
<app-navbar></app-navbar>
<div class="container">
<div class="row my-3">
<div *ngIf="!hasRoute('products/show/:id')" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
<div class="col-sm-6 col-md-8 col-lg-9">
<router-outlet></router-outlet>
</div>
</div>
</div>
<app-footer class="app-footer"></app-footer>
</div>
The problem
For a reason I have been unable to understand, this solution fails, and the sidebar is displayed anywhere on the app.
What am I doing wrong?
<div *ngIf="notProductDetails()" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
HTML ^^^
constructor() {}
public notProductDetails(): void {
return !window.location.pathname.startsWith('/products/show/');
}
TS
Simply use the window location to pull the pathname instead of injecting the router - remove the constructor injection. Also no need to pass in a prop value there, because you only have a single string you are asserting.
In that way, you are running that value just one time. In order to achieve this you can subscribe to the router events like this:
public showBar: boolean = true;
constructor(private readonly router: Router) {
this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe(({ urlAfterRedirects }: NavigationEnd) =>
this.showBar = this.hasRoute(urlAfterRedirects)
);
}
<div *ngIf="showBar" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
In this way, you are updating the showBar value every time the navigation end.
In case someone may find it useful, here is the final solutions I have applied to this problem:
In app\app.component.ts:
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title: string = 'E-commerce';
constructor(private router: Router) {}
ngOnInit() {}
routeIncludesNot(route: string) {
return !window.location.pathname.startsWith(route);
}
}
In app\app.component.html I have:
<div class="app-wrapper">
<app-navbar></app-navbar>
<div class="container">
<div class="row my-3">
<div *ngIf="routeIncludesNot('/products/show/')" class="col-sm-6 col-md-4 col-lg-3">
<app-sidebar class="app-sidebar"></app-sidebar>
</div>
<div [ngClass]="routeIncludesNot('/products/show/') ? 'col-sm-6 col-md-8 col-lg-9' : ''">
<router-outlet></router-outlet>
</div>
</div>
</div>
<app-footer class="app-footer"></app-footer>
</div>
See a "live demo" HERE.
I have a header component and home component. In header component a download button is there, When I click download button the content of home component will be download,so I need to access the div id(content) of home component from header component. I am not getting how to do it.
header.component.html
<button (click)="generarPDF()" type="button" class="btn btn-primary">Download</button>
<nav *ngIf="router.url !== '/' && router.url !== '/login'" class="mb-3 navbar navbar-expand-sm bg-dark-custom navbar-dark">
<!-- Brand/logo -->
<a class="navbar-brand" routerLink="/"><img class="img-responsive" src="../assets/logo.png"></a>
</nav>
header.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router";
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor(public router: Router){}
ngOnInit() {
}
}
home.component.html
<div class="container-fluid" id="content">
<div class="row">
<div class="col-md-6">
<div class="mb-3 text-left">
<div>Total Expenses are: <b>Rs. {{this.sum}}</b></div>
</div>
</div>
<div class="col-md-6">
<div class="mb-3 text-right">
<input [(ngModel)]="searchText" autocomplete="off" class="col-md-6 searchinput" type="text"
placeholder="Search.." />
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered expensetable">
<thead>
<tr>
<th>Date</th>
<th>Treatment</th>
<th>Expenses (INR)</th>
<th>Results</th>
</tr>
</thead>
<tbody>
<ng-container *ngIf="( getListData | filter:searchText) as result">
<tr *ngFor="let item of result">
<td>{{item.Date}}<div><small>({{item.day}})</small></div>
</td>
<td [innerHtml]="getTreatment(item.Treatment)"></td>
<td>{{item.Expenses}}</td>
<td><span placement="left" ngbTooltip="{{item.Description}}" class="{{item.Result}}"><i
class="las la-info-circle info"></i> Info</span></td>
</tr>
<tr *ngIf="result.length === 0">
<td colspan="4" class="text-center">No Data Found</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
</div>
</div>
home.component.ts
import { Component, OnInit,ViewChild, ElementRef} from '#angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import {NgbModal, ModalDismissReasons} from '#ng-bootstrap/ng-bootstrap';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
sum:number;
constructor(private modalService: NgbModal,private commonserviceService: CommonserviceService) { }
#ViewChild('content', { 'static': true}) content:ElementRef;
ngOnInit() {
this.getHeroes();
}
getTreatment(data) {
console.log(data);
let str = '<div class="demooutput">'
let arr = data.split(',');
if (arr.length > 0) {
for (let i = 0; i < arr.length; i++) {
str += '<span class="' + arr[i] + '">' + arr[i] + '</span>'
}
}
str += '</div>'
return str
}
getHeroes(){
this.commonserviceService.getData().subscribe(getListData =>{
this.getListData = getListData;
console.log(this.getListData);
this.sum=0;
for(let a of this.getListData){
this.sum=this.sum+a.Expenses;
}
console.log(this.sum);
},
(error) => {
alert('No data');
}
);
}
generarPDF() {
const div = document.getElementById('content');
const options = {
background: 'white',
scale: 3
};
html2canvas(div, options).then((canvas) => {
var img = canvas.toDataURL("image/PNG");
var doc = new jsPDF('l', 'mm', 'a4', 1);
// Add image Canvas to PDF
const bufferX = 5;
const bufferY = 5;
const imgProps = (<any>doc).getImageProperties(img);
const pdfWidth = doc.internal.pageSize.getWidth() - 2 * bufferX;
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
doc.addImage(img, 'PNG', bufferX, bufferY, pdfWidth, pdfHeight, undefined, 'FAST');
return doc;
}).then((doc) => {
doc.save('postres.pdf');
});
}
}
app.component.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'sampleproject';
}
You can do it using an output/eventEmitter on your parent component, but you would need to include the <app-header> in the home component rather than the app component.
If you want to keep the <app-header> in the app component you'll need another approach, potentially using a service to communicate between the header and the home components.
header.component.html
<button (click)="downloadClicked.emit(null)" type="button" class="btn btn-primary">Download</button>
header.component.ts
export class HeaderComponent implements OnInit {
#Output()
downloadClicked: EventEmitter<any> = new EventEmitter();
constructor(public router: Router){}
ngOnInit() {
}
}
home.component.ts
<app-header (downloadClicked)="generarPDF()"></app-header>
<div class="container-fluid" id="content">
...
app.component.html
<router-outlet></router-outlet>
<app-footer></app-footer>
I have 2 components.
The .html of parent component this is the code:
<div class="space">
<ng-container *ngFor="let item of items">
<ng-container [ngTemplateOutlet]="itemTemplate" [ngTemplateOutletContext]="{item: item}">
</ng-container>
</ng-container>
</div>
<ng-template #itemTemplate let-item="item">
<div class="host">
<img class='card-img-top'
src={{item.image}}
>
<p> </p>
<h6 class="title">{{item.projectTitle}}</h6>
<hr>
<ng-container *ngIf="item.type=='inactive'">
<button id="inactive"
class="btn btn-sm btn-warning py-0 custom-button text-uppercase">{{item.type}}</button>
</ng-container>
</div>
</ng-template>
All code since line: <ng-template #itemTemplate let-item="item">
It's necessary to show in the .html of the child component.
This is the .ts of parent component
import { AfterViewInit, Component, ComponentFactoryResolver, ViewChild, ViewContainerRef, OnInit, TemplateRef, Input, ContentChild } from '#angular/core';
import listProjects from './projects.json';
import { ChildComponent } from './child.component';
#Component({
selector: 'parent-view',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
})
export class ParentComponent {
public items: any = listProjects;
#ContentChild('itemTemplate', { read: TemplateRef }) itemTemplate: ViewContainerRef;
How can show the <ng-template #itemTemplate let-item="item"> in other component?
The solution to this problem:
File: projects-tile-view-components.ts
export class ProjectsTileViewComponent {
#ViewChild('tileViewItems', { static: true }) tileViewItemTemplate: TileViewComponent;
public items = listProjects;
public type = 'etb';
constructor() {}
addItems(e) {
if (this.type === 'osd') {
this.type = 'etb';
} else {
this.type = 'osd';
}
}
}
the file projects-tile-view-components.html
<lib-tile-view [items]="items" #tileViewItems>
<ng-template #tileViewItem let-item>
<div [ngSwitch]="type">
<lib-osd-tile-view-item [item]="item" *ngSwitchCase="'osd'"></lib-osd-tile-view-item>
<lib-osd-tile-view-item [item]="item" *ngSwitchDefault></lib-osd-tile-view-item>
<lib-etb-tile-view-item [item]="item" *ngSwitchCase="'etb'"></lib-etb-tile-view-item>
</div>
</ng-template>
</lib-tile-view>
the file view-item.ts (interface)
export interface ViewItem {
item: any;
}
the file tile-view-components.html
<div>
<ng-container *ngFor="let item of items">
<ng-container *ngTemplateOutlet="tileViewItemTemplate; context: {$implicit: item}">
</ng-container>
</ng-container>
</div>
the file tile-view-item.components.ts
#Component({
selector: 'lib-tile-view',
templateUrl: './tile-view.component.html',
styleUrls: ['./tile-view.component.scss'],
})
export class TileViewComponent {
#Input()
public items: any;
#ContentChild('tileViewItem', { static: true }) tileViewItemTemplate;
}
the file osd-tile-view-components.ts
#Component({
selector: 'lib-osd-tile-view-item',
templateUrl: './osd-tile-view-item.component.html',
styleUrls: ['./osd-tile-view-item.component.scss'],
})
export class OsdTileViewItemComponent implements ViewItem {
#Input() item: any;
public projectView() {
alert('show project');
}
}
the file osd-tile-view-item.components.html
<div class="host" fxFlex="0 1 calc(100% - 32px)" fxFlex.lt-md="0 1 calc(100% - 32px)" fxFlex.lt-sm="100%" (click) = 'projectView()'>
<img class='img-fluid img-thumbnail' src={{item?.image}} alt='logo nih'>
<p> </p>
<h6 class="title">{{item?.projectTitle}}</h6>
<p class="small"><span class="text-muted small text-uppercase">ZIA ID
Number:</span>{{item?.number}}</p>
</div>
Thanks for your help
You need to share this TemplateRef in service (if you want to have access in every component in your application), and then in other component you can read this reference and do something with it - because if you want to pass this reference only to child, then you can use #Input() in child component, but if it should be available across all components, then you need to create service.
service:
#Injectable({
providedIn: 'root'
})
export class TemplateService {
someTemplate: TemplateRef<any>;
}
componentA:
#Component({
selector: 'parent-view',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
})
export class ParentComponent {
public items: any = listProjects;
#ViewChild('itemTemplate', { read: TemplateRef }) set itemTemplate(value) {
this.ts.someTemplate = value;
}
construtor(private ts: TemplateService) {}
}
then in any other component, you can read this template reference
componentB:
#Component({
selector: 'component-b',
templateUrl: './component-b.component.html',
styleUrls: ['./component-b.component.scss'],
})
export class ComponentBComponent {
get itemTemplateReference() {
return this.ts.itemTemplate;
}
construtor(private ts: TemplateService) {}
}
.html of componentB
<ng-container [ngTemplateOutlet]="itemTemplateReference"></ng-container>
And it should render the same <ng-template>
I want to hide the ngb-tab. When i include the ngb-tab the title tab appears on my table head. Is there any way to hide the ngb-tab ??
import { Component, OnInit } from '#angular/core';
import {faCaretLeft} from "#fortawesome/free-solid-svg-icons";
#Component({
selector: 'app-address-book-container',
templateUrl: './address-book-container.component.html',
styleUrls: ['./address-book-container.component.scss']
})
export class AddressBookContainerComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
This is my html
<div class="container mt-5 ">
<div class="row">
<ngb-tabset>
<ngb-tab >
<ng-template ngbTabContent>
<app-address-book-table></app-address-book-table>
</ng-template>
</ngb-tab>
</ngb-tabset>
</div>
</div>
You can use the *ngIf statement to hide it, I declared as "false" but you can put a variable boolean in order to change when is true or false.
<div class="container mt-5">
<div class="row">
<ngb-tabset>
<ngb-tab *ngIf="false">
<ng-template ngbTabContent>
<app-address-book-table></app-address-book-table>
</ng-template>
</ngb-tab>
</ngb-tabset>
</div>
</div>
I have an array of Google Map Embed API URLs. However, when iterating over each item and binding them to the source of an iFrame.
I could use the following.
constructor(private sanitizer: DomSanitizationService) {
this.url = sanitizer.bypassSecurityTrustResourceUrl('https://www.google.com/maps/embed/v1/place?key=KEY&q=365 Badger Ave, Newark, New Jersey 07112');
}
But, I would have to do this for each item and I can't do so since I receive the array from an external source that updates.
How could I bypass the security for each of my URLs?
Here's app.component.ts
import { Component, Pipe } from '#angular/core';
import { DomSanitizationService } from '#angular/platform-browser';
#Pipe({name: 'secureUrl'})
export class Url {
constructor(private sanitizer:DomSanitizationService){
this.sanitizer = sanitizer;
}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url).changingThisBreaksApplicationSecurity;
}
}
#Component({
selector: 'my-app',
pipes: [Url],
template: `
<div class="container">
<div style="padding-top: 20px">
<div class="row" *ngFor="let row of rows">
<div *ngFor="let event of row">
<div class="col s12 m6 l4">
<div class="card hoverable">
<div class="card-image waves-effect waves-block waves-light">
<img height="300" class="activator" [src]="event.thumbnail">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">{{event.title}}</span>
<p><a class="activator">Hosted by {{event.host.data.first_name}} {{event.host.data.last_name}}</a></p>
</div>
<div class="card-action grey lighten-2">
<a class="blue-grey-text lighten-3">Details</a>
<a class="blue-grey-text lighten-3">Join</a>
</div>
<div class="card-reveal" style="font-size: 15px">
<span class="card-title grey-text text-darken-4"><center>{{event.title}}</center><i class="material-icons right">close</i></span>
<hr>
<center>
<p class="truncate">{{event.description}}</p>
<hr>
<p>Starts {{event.start}}</p>
<iframe width="210" height="190" frameborder="0" style="border:0" src="{{event.address|secureUrl}}" allowfullscreen></iframe>
</center>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
`
})
export class AppComponent {
public rows = GROUPS;
}
var EVENTS = [
{
id: 95,
title: "Event Name",
description: "The awesome event description",
thumbnail: "https://ucarecdn.com/58955d6b-bd4c-41f3-8a7b-4ce2bf013b13/IMG_4229.JPG",
access: "public",
code: null,
start: "1 week ago",
end: "6 days ago",
address: "https://www.google.com/maps/embed/v1/place?key=KEY",
host: {
data: {
id: 23,
avatar: "http://www.gravatar.com/avatar/9e557072ab393aa2fca6701eb7b23853?s=45&d=mm"
}
},
category: {
data: {
id: 1,
title: "Wedding",
description: "A marriage ceremony."
}
}
}
];
var chunk_size = 3;
const GROUPS = EVENTS.map(function(e,i){
return i%chunk_size===0 ? EVENTS.slice(i,i+chunk_size) : null;
})
.filter(x=>!!x)
You can use PIPE with DomSanitizationService as shown below;
//our root app component
import {Component, Pipe} from '#angular/core'
import {DomSanitizationService} from '#angular/platform-browser';
#Pipe({name: 'secureUrl'})
export class Url {
constructor(private sanitizer:DomSanitizationService){
this.sanitizer = sanitizer;
}
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url).changingThisBreaksApplicationSecurity;
}
}
#Component({
selector: 'my-app',
pipes: [Url],
template: `
<div *ngFor="let item of myUrls; let i = index">
{{item.url|secureUrl}}
</div>
`,
})
export class AppComponent {
myUrls=[{url:"google.com"},{url:"google1.com"},{url:"google2.com"}];
}