how to add social share button in angular 4 - html

I have run the command "npm install --save ng2-social-share".
and then add into app.module.ts :-
import { CeiboShare } from 'ng2-social-share';
#NgModule({
imports: [
CeiboShare
]
});
and then i add into my home.component.ts :-
import { CeiboShare } from 'ng2-social-share';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
directives: [CeiboShare]
})
webpack: Compiling...
ERROR in src/app/home/home.component.ts(16,3): error TS2345: Argument of type '{ selector: string; templateUrl: string; styleUrls: string[]; directives: typeof CeiboShare[]; }' is not assignable to parameter of type 'Component'.
Object literal may only specify known properties, and 'directives' does not exist in type 'Component'.
Date: 2018-02-27T09:02:42.288Z - Hash: bedb972b22f9a72ebb59 - Time: 2832ms
5 unchanged chunks
chunk {main} main.bundle.js (main) 367 kB [initial] [rendered]
webpack: Compiled successfully.

The simple way for you is to import in your app.modules.ts like this
1) import {CeiboShare} from 'ng2-social-share';
#NgModule({
declarations: [
AppComponent,
CeiboShare
]
})
2) and then in your home.component.ts
you need to just only define the url sharing link and image url sharing if you want like this:
//vars used only for example, put anything you want :)
public repoUrl = 'https://www.egozola.com';
public imageUrl = 'https://avatars2.githubusercontent.com/u/10674541?v=3&s=200';
the in your home.component.html the you can call sharing easily like this
button ceiboShare [facebook]="{u: repoUrl}">Facebook
Linkedin
Google Plus
Twitter
Pinterest
good all thing is working well

What you could do is to use these functions on your typescript file and call it from the template.
Providing here 5 Social Media Share - Facebook, Pinterest, Twitter, GooglePlus, LinkedIn
// Facebook share won't work if your shareUrl is localhost:port/abc, it should be genuine deployed url
shareOnFacebook(shareUrl: string) {
shareUrl = encodeURIComponent(shareUrl);
window.open(`https://www.facebook.com/sharer/sharer.php?u=${shareUrl}`, 'sharer');
}
shareOnPinterest(shareUrl: string, img: string, desc: string) {
shareUrl = encodeURIComponent(shareUrl);
img = encodeURIComponent(img);
desc = encodeURIComponent(desc);
window.open(`https://www.pinterest.com/pin/create/button?url=${shareUrl}&media=${img}&description=${desc}`, 'sharer');
}
shareOnTwitter(shareUrl: string, desc: string) {
shareUrl = encodeURIComponent(shareUrl);
desc = encodeURIComponent(desc);
window.open(`https://twitter.com/intent/tweet?url=${shareUrl}&text=${desc}`, 'sharer');
}
shareOnGooglePlus(shareUrl: string) {
shareUrl = encodeURIComponent(shareUrl);
window.open(`https://plus.google.com/share?url=${shareUrl}`, 'sharer');
}
// LinkedIn share won't work if your shareUrl is localhost:port/abc, it should be genuine deployed url
shareOnLinkedIn(shareUrl: string, title: string, summary: string) {
shareUrl = encodeURIComponent(shareUrl);
window.open(`https://www.linkedin.com/shareArticle?url=${shareUrl}&title=${title}&summary=${summary}`, 'sharer');
}
Hope this will help you or somebody else.
Thanks!

remove that directives : [CeiboShare] from #component decorator. It is not supported in angular 4 and you don't even need to import it into your component. Just Import into Ngmodule as below,
import { CeiboShare } from 'ng2-social-share';
#NgModule({
imports: [
CeiboShare.forRoot()
]
});
This would suffice to get it working in any component as attribute directives.

Related

Angular 6 return JSON result intead of HTML template

Is it possible to return JSON result from Angular instead of the HTML template coz we want to build something similar to a API-server? Thanks.
Here is the example that return the HTML template, how can we just return JSON without using template?
What I want to return is just a simple json result instead of HTML.
{"ID" : "1", "Name" : "Apple"}
Here is the code.
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-noresultsfound',
templateUrl: './noresultsfound.component.html',
styleUrls: ['./noresultsfound.component.css']
})
export class NoresultsfoundComponent implements OnInit {
#Input() txtval: string;
constructor(private app: AppConstants) { }
noresultsfound = this.app.noresultsfound;
ngOnInit() {
}
}
Alex
I think, he meant that pure JSON should be returned to who ever requested it by endpoint request. At least i faced something like this.
For static json, i've found an answer: https://github.com/angular/angular-cli/issues/5029
bresleveloper commented on 6 Jul 2018
1. ng-build with your index.html set properly with its components. (or conditional app-components)
2. rename and copy the rendered to (for example) /src/search.html
3. in angular.json (angular-cli.json for pre v5) find "assets":
"assets": [
"src/favicon.ico",
"src/search.html",
"src/assets"
],
browse localhost:4200/search.html
enjoy :)
Interesting part comes when u try to generate that json somehow, with browser not being involved - like some automatic service sends a request to some angular endpoint, like: hosname/statistics and in response, it receives a json which depends on number of pictures and headers on this current hosname, like {siteName: 'test', pictures: 10, headers: 1}.

How to navigate to other page in angular 6?

Im trying to redirect my page from login to another page. Im following this code.
My login component ts file:
import { Router } from '#angular/router';
constructor(private router: Router) {
}
funLogin(mobilenumber){
this.router.navigateByUrl('registration');
}
In my html Im calling this function in a submit btn,
<button class="common-btn btn" (click)="funLogin(mobileNo.value)">Submit</button>
In my app.login.routing file,
export const loginRouting: Routes = [
{
path: '', component: DashboardRootComponent, canActivateChild: [],
children: [
{ path: '', component: DashboardComponent, pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'registration', component: RegistrationComponent },
]
}
]
I have tried with "this.router.navigate" & referredlot of links. But it didnt work. Can anyone please tell me where Im going wrong or if you could give me a workingh sample it would be better.
#sasi.. try like this,
<a routerLink="/registration"><button class="btn btn-success" > Submit </button></a>
Update :
In order to use the routing in your application, you must register the components which allows the angular router to render the view.
We need register our components in App Module or any Feature Module of it (your current working module) in order to route to specific component view.
We can register components in two ways
.forRoot(appRoutes) for app level component registration like
featuteModules(ex. UserManagement) and components which you want register at root level.
.forChild(featureRoutes) for feature modules child components(Ex. UserDelete, UserUpdate).
you can register something like below,
const appRoutes: Routes = [
{ path: 'user', loadChildren: './user/user.module#UserModule' },
{ path: 'heroes', component: HeroListComponent },
];
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(
appRoutes
)
],
P.S : In order to navigate from one component to another, you must include the RouterModule in corresponding Module Imports array from #angular/router package.
You can navigate one to another page in Angular in Two ways. (both are same at wrapper level but the implementation from our side bit diff so.)
routerLink directive
routerLink directive gives you absolute path match like navigateByUrl() of Router class.
<a [routerLink]=['/registration']><button class="btn btn-success" > Submit </button></a>
If you use dynamic values to generate the link, you can pass an array of path segments, followed by the params for each segment.
For instance routerLink=['/team', teamId, 'user', userName, {details: true}] means that we want to generate a link to /team/11/user/bob;details=true.
There are some useful points to be remembered when we are using routerLink.
If the first segment begins with /, the router will look up the route
from the root of the app.
If the first segment begins with ./, or doesn't begin with a slash,
the router will instead look in the children of the current activated
route.
And if the first segment begins with ../, the router will go up one
level.
for more info have look here.. routerLink
Router class
We need inject Router class into the component in order to use it's methods.
There more than two methods to navigate like navigate() , navigateByUrl(), and some other.. but we will mostly use these two.
navigate() :
Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.
this.route.navigate(['/team/113/user/ganesh']);
navigate() command will append the latest string is append to existing URL. We can also parse the queryParams from this method like below,
this.router.navigate(['/team/'], {
queryParams: { userId: this.userId, userName: this.userName }
});
You can get the these values with ActivatedRoute in navigated Component. you can check here more about paramMap, snapshot(no-observable alternative).
navigateByUrl()
Navigate based on the provided URL, which must be absolute.
this.route.navigateByUrl(['/team/113/user/ganesh']);
navigateByUrl() is similar to changing the location bar directly–we are providing the whole new URL.
I am using angular 7 and I solved it in this way into my project.
1.First We need to implement this Modules to our app.module.ts file
import { AppRoutingModule} from './app-routing.module';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
],
})
2.Then Open your.component.html file and then fire a method for navigate where you want to go
<button class="btn btn-primary" (click)="gotoHome()">Home</button>
3.Then Go your.component.ts file for where you want to navigate. And add this code there.
import { Router } from '#angular/router';
export class YourComponentClassName implements OnInit {
constructor(private router: Router) {}
gotoHome(){
this.router.navigate(['/home']); // define your component where you want to go
}
}
4.And lastly want to say be careful to look after your app-routing.module.ts
where you must have that component path where you want to navigate otherwise it will give you error. For my case.
const routes: Routes = [
{ path:'', component:LoginComponent},
{ path: 'home', component:HomeComponent }, // you must add your component here
{ path: '**', component:PageNotFoundComponent }
];
Thanks I think, I share all of the case for this routing section. Happy Coding !!!
navigateByUrl expects an absolute path, so a leading / might take you to the right page
You could also use navigate and don't need the leading / but the syntax is slightly different as it expects an array for the path
https://angular.io/api/router/Router#navigateByUrl
<a class="nav-link mt-1" [routerLink]="['/login']"><i class="fa fa-sign-in"></i> Login</a>

Can't set up routing to a named outlet in Angular

I have three named router outlets as shown below.
...
<router-outlet name="menus"><router-outlet>
<router-outlet><router-outlet>
<router-outlet name="footer"><router-outlet>
...
In the markup I want to route the first one, menus, to a component with certain submenu junk in it as shown in the docs.
<ul *ngFor="let main of menus;"
routerLink="[{outlets:{menus:[{{main.link}}]}}]"
class="nav-items">{{main.header}}
The error I'm getting says that:
Error: Cannot match any routes. URL Segment: '%5B%7Boutlets:%7Bmenus:%5Bsubmenu1%5D%7D%7D%5D'
Am at a loss what's wrong with the syntax. Googling my fingernails off but haven't found a simple and crude example of a routerLink version showing how to point a route in a named outlet.
Edit: Based on the comments and samples, I need to reformulate the code being used, still with the same error. In the markup:
<ul *ngFor="let main of menus;"
(click)="pullMenu(main.link)"
class="nav-items">{{main.header}}
Then, in TS:
constructor(private router: Router, private route: ActivatedRoute) { }
pullSubmenu(input) {
console.log(input);
this.router.navigate(
[{ outlets: { menus: [input] } }],
{ relativeTo: this.route });
}
Now, I'm getting the following error (submenu1 is the name of configured path).
Error: Cannot match any routes. URL Segment: 'submenu1'
My routing is set up in the module like this.
const routes: Routes = [
{ path: "submenu1", component: Submenu1Component },
{ path: "submenu2", component: Submenu2Component }
];
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
MainAreaComponent,
Submenu1Component,
Submenu2Component
],
imports: [
BrowserModule,
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You need to use the evaluated version [routerLink]:
<ul *ngFor="let main of menus;"
[routerLink]="[{outlets:{menus:[{{main.link}}]}}]"
class="nav-items">{{main.header}}
As an alternative you can emulate the routerLink. Here is the gist of what it does:
#HostListener('click')
onClick(): boolean {
const extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
So, here is the setup using navigate instead of navigateByUrl:
#Component({
template: `
<ul *ngFor="let main of menus;" (click)="[{outlets:{menus:[{{main.link}}]}}])"
class="nav-items">{{main.header}}
`
...
class MyComponent {
constructor(router: Router, route: ActivatedRoute) {}
navigate(commands) {
this.router.navigate(commands, {relativeTo: this.route})
You can't use unevaluated version of routerLink because it reads commands as a string and if you have outletsin the commands strings don't work. See Navigation to secondary route URL for routerLink attribute to understand why.

Not able to display google maps on VS 2015 using angular 2

this is my component:
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
styles: [`.sebm-google-map-container {
height: 300px;}`],
template: `<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
</sebm-google-map>`})
just a simple example to display the map. But all this does is display the content in the (my-app) tag.
and the module is :
import { AgmCoreModule } from 'angular2-google-maps/core';
#NgModule({
imports: [
.
.
.
AgmCoreModule.forRoot({
apiKey: 'MY_API_KEY'
})
],
the value of lat and lang i'm getting from AppComponent.
export class AppComponent {
title: string = 'My first angular2-google-maps project';
lat: number = 51.678418;
lng: number = 7.809007;}
I have been successful in implementing this same code using console(angular2 cli) but when I tried this using Visual Studio 2015 it is not displaying the maps. To be specific it only shows the content in the anchor tag in index.html.
plus I would to mention I am to able to run angular2 Quickstart on VS 2015.
If anyone can point out what I am doing wrong or have some suggestion it would be really helpful.
Solution to this was just downgrading the version of angular2-google-maps in project.json from 0.17.0 to 0.16.0.

Saving dates in Angular 2 and JSON

This has been a very difficult problem I have run into with my Angular 2 app. I am trying to format my API (MongoDB) so that each new "post" added by the admin can be fetched by the DATE (not time) by the front end. For example, my schema looks like this:
{name: "The best product ever",date: "25092016",quantity: 345},{name:"The okayest product ever",date: "26092016",quantity: 544,}
As you can tell, the date property is a single number. I then have a function that fetches the data from the object with the current date. However, this is the problem. The date format I am using for the JSON is 'ddMMyyyy'. This worked well for the date pipe in the HTML template, but I cannot seem to be able to format any date in a variable to match this format, or a similar format. All the dates in Angular 2 classes show GMT and timestamps, etc.
How to I format a date in Angular 2 components to match a short succinct string format?
You can use that DatePipe even in your code. :)
https://plnkr.co/edit/6pbHMVSTmndvs9CqYYUL?p=preview
import {Component, NgModule} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import {DatePipe} from '#angular/common';
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
let dp = new DatePipe('de-DE' /* locale .. */);
this.name = dp.transform(new Date(), 'ddMMyyyy');
console.log(name);
}
}
#NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Or you want to use a library like Moment.js..