Navigating between components in different modules using Angular 5

I have a home component within the homeModule and a contactUs component within the contactModule.

When I click cancel on the contactUs component, it should redirect me to the Home component.

Here are the routes:

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {homeComponent} from './home/home.component';


const routes: Routes = [
{ path: 'home', component: homeComponent},
{ path: 'demo-ui/home', component: homeComponent},
];


@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule],
declarations: []
})
export class AppHomeRoutingModule {
}

I attempted the following code but it did not work

 import { Component, OnInit } from '@angular/core';
 import { FormsModule, Validators, NgForm } from '@angular/forms';
 import { Router } from '@angular/router';


 @Component({
   //some code
 })
export class contactUsComponent implements OnInit {
constructor( private router: Router ){
}

ngOnInit() {
}


redirect(){
this.router.navigateByUrl('/home');    }

}
 //html
 <button class="btn btn-primary" type="button"  (click)="redirect()"> 
  Cancel </button>

I also tried

<button class="btn btn-primary" type="button"  [routerLink]="['/home']"> Cancel </button>

and

<button class="btn btn-primary" type="button"  routerLink="/home"> Cancel </button>

Error: Cannot match any routes. URL Segment './home'

Answer №1

In order for routerLink to function properly, you must include an anchor tag.

<a class="btn btn-secondary" role="button" routerLink="/dashboard">Go back</a>

Answer №2

To implement a function in your .ts file, follow these steps:

Firstly, create the function like this:

goToHomePage(){
   this.router.navigate(['/home']);
}

Then, you can call this function in your HTML code as shown below:

<button (click)="goToHomePage()">Go to Home</button>

Answer №3

To navigate to the home page, you can simply use: this.router.navigate(['home']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state. My goal is to specifically fetch the 'numberOf ...

How can we update the information in the initial observable using data from a separate observable, taking into consideration specific conditions in Angular with RxJS?

Encountered a scenario where I need to fetch data from an API (e.g. cars via getCars()) that returns Observables and then get additional data by car model (e.g. features via getFeatures(model)) in order to replace the features data for each car. In relati ...

Distinguishing between keydown.enter for textareas in Angular on mobile and desktop devices

As I work on developing a chat platform, one of the key features is the message input box using a textarea where users can type their messages. Currently, pressing the Enter key allows the user to send a message. However, I am curious to explore if it&apos ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

What causes the typings for Partial Record to be undefined when using Object.values?

When I retrieve Object.values from a Partial Record, the values consist of a combination of what I anticipated and undefined. const example: Partial<Record<string, number>> = {} const values = Object.values(example) // The type for values is u ...

Eliminating Redundant Code in Angular by Utilizing RxJS Subscriptions in a Service with Proper Typing and Unsubscribing

I've noticed some repetitive code in a few of my components... After simplifying it, the code basically looks like this: // code within my components phoneNumberChanges$: any; ngOnInit(): void { // keep an eye on the phone number this.subscri ...

Exploring ways to conduct a thorough scan of object values, inclusive of nested arrays

My goal is to extract all values from an object. This object also includes arrays, and those arrays contain objects that in turn can have arrays. function iterate(obj) { Object.keys(obj).forEach(key => { console.log(`key: ${key}, value: ${o ...

Can you change the method definition of a built-in class using TypeScript?

Working with the Web Audio Api in TypeScript has presented me with a minor issue. I am trying to enhance AudioParam's prototype by adding some convenience methods that can be used on any parameter. However, I keep getting an error from the compiler st ...

Creating a tsconfig.json file that aligns perfectly with your package.json and tsc command: a step-by-step

I've chosen to use TodoMvc Typescript-Angular as the starting point for my AngularJS project. Everything is working smoothly so far. Here's a breakdown of what I can do: To manage all dependencies, I simply run npm install or npm update based o ...

Creating an Angular Directive for Setting the Tab Index on Enter Key Press

I need assistance with firing the Tab key event on keydown.Enter in an entire form. Currently, I am running the functions on the parent Div using the following code. Although the event is detected in the console, no changes occur on the input field (i.e., ...

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

Retrieving subcollection data in Firestore using Angular

I am facing the challenge of extracting data from a subcollection within my database structure. Within my main collection products, there are documents that have a nested subcollection called reviews. products/prodID/reviews/reviewID Here is my interface ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

The Angular Syncfusion schedule is unable to call upon an object that may potentially be 'undefined'

Currently, I am developing an application using Angular Syncfusion to allow users to view and book appointments. I found a helpful resource at the following link: Below you can find the code snippet I have been working on: <ejs-schedule #scheduleObj ...

Encountering an issue with Angular's <base href="/projectname/client"> directive causing an error in the index.html file

I am currently working on an Angular 7 application that is deployed on Openshift using a Docker image. I have been trying to configure the application URL to be https://ocp-1123/projectname/client, but whenever I set my base href with "/projectname/client" ...

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...

To work on React with typescript, your Type must include a method '[Symbol.iterator]()' that will fetch an iterator

Here is a demonstration I have prepared for you: https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx Apologies for the lack of clarity in my question, but... The demo I created showcases a basic shopping cart using React and Typescri ...

What is the recommended default value for a file in useState when working with React and TypeScript?

Can anyone help me with initializing a file using useState in React Typescript? const [images, setImages] = useState<File>(); const [formData, setFormData] = useState({ image: File }); I'm facing an issue where the file is sho ...

Troubleshooting property assignment issues within an Angular service

I have created a simple injectable service in TypeScript for Angular 4. This service is designed to fetch a JSON file from the network and store the data as an array in its property called data. Other classes can then access this data using the method getD ...