I have checked the stack over flow answers on this, but none of them seem to be relevant, I have created two components page1 and page2. and declared a route in the module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Route, RouterModule} from '@angular/router'
import { AppComponent } from './app.component';
import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';
@NgModule({
declarations: [
AppComponent,
Page1Component,
Page2Component
],
imports: [
BrowserModule,
RouterModule.forRoot([
{path:'page1', component:Page1Component},
{path:'page2', component:Page2Component}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
And my page1 html is as below
<p>
page1 works!
<button (click)= 'OnbtnClick()'>Route to Page2</button>
</p>
The Component ts is as below
import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';
@Component({
selector: 'app-page1',
templateUrl: './page1.component.html',
styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit {
constructor(private _router:Router) { }
ngOnInit() {
}
OnbtnClick()
{
let abc =this._router.navigate(['/page2'])
}
}
But on clicking the button, The Url is changing, But the view remains the same, The appcomponent.html is as follows.
<div style="text-align:center">
<h1>
Welcome to SuperHero!
</h1>
</div>
<app-page1></app-page1>
Please help !!
Angular 4 - Routing. Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components. We have already seen how to create a component.
With the help of the @ViewChild decorator, angular makes it very easy to reference specific child elements (html nodes or components) of your component. All you need to do is to add a reference identifier to the node or component inside of your template.
The most common reason, is, that the browser has not finished creating it and has not yet added it to the DOM. If you try to use it before it has been added, it will not work and crash your app. If you are familiar with JavaScript in general, you have probably stumbled across that problem, as it is not specific to angular.
Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components.
AppComponent.html needs to have <router-outlet></router-outlet>
directive:
<div style="text-align:center">
<h1>
Welcome to SuperHero!
</h1>
</div>
<-- The view is injected here -->
<router-outlet></router-outlet>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With