How to create simple redirect on click on some button in Angular 2? Already tried:
import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
#Component({
selector: 'loginForm',
templateUrl: 'login.html',
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
You could leverage the event support of Angular2:
import {Router} from '#angular/router';
#Component({
selector: 'loginForm',
template: `
<div (click)="redirect()">Redirect</div>
`,
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
redirect() {
this.router.navigate(['./SomewhereElse']);
}
}
I would make it more dynamic using method parameters
Import the angular router
import { Router } from '#angular/router';
Create a button with click event
<div (click)="redirect(my-page)">My page</div>
Create a method with a pagename parameter
redirect(pagename: string) {
this.router.navigate(['/'+pagename]);
}
When clicked the router should route to the correct page
I'd say use routerLink directive & placed that over a(anchor) tag
<a [routerLink]="['./SomewhereElse']">Redirect</a>
Also you need to remove ROUTER_PROVIDERS from providers & include it in bootstrap dependency and then add ROUTER_DIRECTIVES in directives option of component to use routerLink directive on HTML. Make sure RouterModule with its route has been injected in Main App module.
Try routerLinkon button tag
<button type="button" [routerLink]="['/edit']">Edit</button>
More Info
in your html file right this code.
<button (click)="btnClick()">Cancel</button>
in your component.ts file right this code.
constructor(private router:Router) { }
btnClick(){
this.router.navigateByUrl("/payment");
}
window.location.reload();
does the trick
Related
I added OpenRouteService to my Stackbliz application but cant get it working.
the Component looks like:
import { Component, OnInit } from '#angular/core';
import {Location} from '#angular/common';
import {Openrouteservice} from '/openrouteservice-js/dist/ors-js-client';
#Component({
selector: 'app-event-plan',
templateUrl: './event-plan.component.html',
styleUrls: ['./event-plan.component.scss']
})
export class EventPlanComponent implements OnInit {
constructor(private _location: Location) {
console.log("++++")
console.log(Openrouteservice)
}
ngOnInit() {
}
backClicked() {
this._location.back();
}
}
My problem is that it just doesnt get loaded. I added it as a dependency in the dependency section.
I made the project public here is the url - https://stackblitz.com/edit/angular-micwge?file=src%2Fapp%2Fevent-plan%2Fevent-plan.component.ts
You will have to change the way you import the library. The current way you import is looking for a named export from the library.
If you have allowSyntheticImports and esModuleInterop in your tsconfig.json use this:
import Openrouteservice from 'openrouteservice-js';
otherwise:
import * as Openrouteservice from 'openrouteservice-js';
Find your forked stacknlitz
I want to run a function inside component every time user switch to this component. I tried to use ngOninit (run function inside only once) and other methods like ngOnComponentInit etc. but none of these worked for me.
Maybe I want to do this in a wrong way...
Please advice.
edit:
some example code.
home.component.ts
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../auth/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private auth: AuthService, private router: Router) {}
ngOnInit() {
if(this.auth.token == null){
this.router.navigate((['/']));
}
}
someFunction(){
console.log("ok");
}
}
I want to run someFunction() everytime user switch to this component.
Do you mean onFocus()? This is what gets called when a user clicks on or tabs into a component.
I have an Angular2 application and I want to use Semantic UI. However, there are some jQuery configurations like below that I have to run after a component loaded:
$('#app .ui.sidebar')
.sidebar({context:$('#app')})
.sidebar('setting', 'transition', 'overlay')
It is not working by importing the js file in the head of index.html or writing it in a <script> tag inside of a component template. Is there a "typescript way" to do that or how can I use a js file inside of a component?
I found this link about using jQuery in directives, then I created a sidebar directive:
import {Directive, ElementRef, OnDestroy, OnInit, Input} from '#angular/core';
import {HostListener} from "#angular/core/src/metadata/directives";
declare var $: any
#Directive({
selector: '.ui.sidebar'
})
export class SidebarDirective implements OnInit, OnDestroy {
#Input() context: string;
constructor(private el: ElementRef) {
}
public ngOnInit() {
$(this.el.nativeElement)
.sidebar({context: this.context})
.sidebar('setting', 'transition', 'overlay');
}
public ngOnDestroy() {
}
}
Then, I used it in the template:
<div id="app">
<div context="#app" class="ui left vertical menu sidebar"></div>
<div class="pusher"></div>
</div>
I have spent quite some time to get this working although it is rather simple in the end. Hope to save you some time ...
There is no need to create a directive, you can use the jQuery command as you would use with JavaScript (described at https://semantic-ui.com/modules/sidebar.html#/usage). However, "$" has to be declared and the command has to be located in a TypeScript function ("toggle()"):
import {Component} from '#angular/core';
declare var $: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
toggle() {
$('.ui.sidebar').sidebar('toggle');
}
}
The corresponding section of the template may look like this:
<div class="ui fixed inverted main menu">
<a (click)="toggle()" class="launch icon item">
<i class="content icon"></i>
<p style="padding-left:1em">Menu</p>
</a>
</div>
Don't forget to add jQuery to the scripts section of .angular-cli.json:
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/semantic-ui-css/semantic.min.js"
],
I'm using Semantic UI 2.2.12 which already depends on jQuery 3.2.1. Angular version is 4.4.4 running on node.js 6.11.2.
import { Component, OnInit } from '#angular/core';
declare var $:any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app works!';
ngOnInit(){
$('#app .ui.sidebar')
.sidebar({context:$('#app')})
.sidebar('setting', 'transition', 'overlay') ;
}
}
I am taking my first steps with Angular 2 and angular in general, and I am wondering how to setup a landing page.
My goal is to show a landingpage everytime the user does not have a token in local storage or in a cookie.
My app.component.ts looks like this
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteConfig} from 'angular2/router';
import {NavbarComponent} from './navbar.component';
import {LoaderComponent} from './loader.component';
import {NameListService} from '../shared/index';
import {HomeComponent} from '../+home/index';
import {AboutComponent} from '../+about/index';
#Component({
selector: 'g-app',
viewProviders: [NameListService],
templateUrl: 'app/components/app.component.html',
directives: [ROUTER_DIRECTIVES, NavbarComponent, LoaderComponent]
})
#RouteConfig([
{
path: '/',
name: 'Home',
component: HomeComponent
},
{
path: '/about',
name: 'About',
component: AboutComponent
}
])
export class AppComponent {
}
/home and /about are also components if I understand correctly. Now I would like to have a seperate page that doesn't have access to the navbar. Which is what the user will always land on if he isn't logged in.
Would be awesome if someone could help me start out or atleast point me in a good direction, maybe point me to a good angular 2 tutorial.
This is the boilerplate I am basing my app on https://github.com/mgechev/angular2-seed
You can override the router-outlet and check on activation, if the token is present. Something like this:
import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';
#Directive({
selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
publicRoutes: any;
private parentRouter: Router;
constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader,
_parentRouter: Router, #Attribute('name') nameAttr: string) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.parentRouter = _parentRouter;
}
activate(instruction: ComponentInstruction) {
if (!hasToken()) {
this.parentRouter.navigateByUrl('/login');
}
return super.activate(instruction);
}
}
Adapted from here: https://github.com/auth0-blog/angular2-authentication-sample/blob/master/src/app/LoggedInOutlet.ts
This can be extended to be able to work with roles and other access controlls.
You can just redirect to a specific route on load when the token is not available.
export class AppComponent {
constructor(private router:Router) {
if(!hasToken()) {
router.navigate(['/LoginForm']);
}
}
}
Alternatively you can create a custom RouterOutlet that checks for each route if it is allowed for the user to navigate to that route like explained in http://www.captaincodeman.com/2016/03/31/angular2-route-security/
Is it possible to switch pages without having to click a [router-link]="" html element?
EDIT: Updated code which is Working
import {Component, View} from 'angular2/angular2';
import {Router} from 'angular2/router';
#Component({
selector: 'menu'
})
#View({
templateUrl: '/views/menu.html',
directives: []
})
export class Menu {
constructor(public router: Router) {
}
navigate() { // Called by (click)= on element in .html
this.router.navigate(['/Net_int_config']);
}
}