Tips for connecting a separate page to a button in Angular?

What is the best way to connect a login component to a button on the home page in Angular, so that it opens up a login page?

I have attempted to achieve this by creating a click event for the login button within myaccount-dropdown component in my-account-dropdown.html:


      <a href="#" class="sub-menu-link">
        <button (click)="navigateToLogin('login')">Login</button>
      </a>

In my-account-dropdown.ts:


export class MyAccountDropdownComponent {
  isMenuOpen: boolean = false;

  toggleMenu(): void {
    this.isMenuOpen = !this.isMenuOpen;
  }

  constructor(private router: Router) {}

  navigateToLogin(pagename: string):void {
    this.router.navigate([`${pagename}`]);
}
}

In app-routing.module.ts:


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from '../app/login/login.component'; 

const routes: Routes = [
  // Other routes
  { path: 'login', component: LoginComponent }, 
];

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

I have also created header and footer components and linked them to the home page in app.component.html. However, when I click the login button, the login page flickers and appears under the homepage. How can I make sure that only the login page is displayed when the button is clicked? Where should I properly link it?

Answer №1

It appears that your my-account-dropdown.html file is in good shape.
For the my-account-dropdown.ts file, make sure to implement the function like this:-
navigateToLogin():void {
  this.router.navigate(['/login']);
}

The app-routing.module.ts file seems to be correct as well.

To enhance the structure of your project, modify the following sections in the app html and app.ts files:

App component.ts file:-
Start by initializing - routerChangeSubscription: Subscription | undefined;
In the constructor, invoke a function - this.getRouterChangeSubscription();
Define the mentioned function:
getRouterChangeSubscription(): void {
    this.routerChangeSubscription = this.router.events.subscribe((route: any) => {
      if (route instanceof NavigationEnd) {
        if (route.url === '/' || route.url === '/login') {
          this.isShow = false;
        }
        else {
          this.isShow = true;
        }
      }
    });
  }
  
App component.html :-
<div *ngIf='this.show'>
    <app-header></app-header>
</div>
<router-outlet></router-outlet>
<div *ngIf='this.show'>
    <app-footer></app-footer>
</div>

By applying these changes, when you navigate to the login page, only the login UI will be displayed. The header and footer UI will be hidden with the use of the this.show variable.

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

Solving non-square thumbnail display in a square space using only CSS3

I have a non-square image that I need to scale to fit into a 200px x 200px box. How can I achieve this using CSS or CSS3? The scaling must maintain the aspect ratio of the image It should work for both portrait and landscape orientations Chopping of the ...

Ways to Conceal Information in Angular2

On my website, I have a layout with three tabs. In the third tab, I've implemented an ng-select tag. My goal is to only display the 1st ng-select tag initially, while keeping the other two hidden until the user selects data in the 1st tag. For referen ...

Best way to observe something

For the project I am currently working on, I have an observable that returns values and I need to update my local variable based on the value returned by this observable. I have identified two possible ways to achieve this: directly subscribing to the obs ...

Attempting to extract a parameter from a URL and pass it as an argument to a function for the purpose of locating objects based on

I am trying to retrieve data from a URL http://localhost:3000/share/user=sampleuser to display objects with an author value that matches the one in the URL. However, I encountered an error when attempting to call a function that extracts the value from t ...

Tips for utilizing the useEffect hook to update a state while avoiding an endless cycle of re-renders

I currently have the following state: const [doctor, setDoctor] = useState<doctorStateProps | null>(null) And then I implemented a useEffect function like this: useEffect(() => { if(!doctor){ axios.get(`doctor/${id}`).then(({d ...

Creating Concurrent Svelte Applications with Local State Management

Note: Self-answer provided. There are three primary methods in Svelte for passing data between components: 1. Utilizing Props This involves passing data from a parent component to a child component. Data transfer is one-way only. Data can only be passed ...

Dynamically Loading External JavaScript Files Depending on User Input

Looking for guidance on how to dynamically load a single javascript file out of several options based on user input in an HTML code. Any suggestions on how to achieve this task? Thank you! ...

Access dynamic content from Tinymce 4.x without any manual effort

Is there a way to extract the HTML content from a tinyMCE editor and display it on a page without using the tinyMCE editor itself? I know about the getcontent() function in tinyMCE, but is there another function, parameter, or plugin that can be used to ...

Tips for setting a default value in a generic function in TypeScript, where the default argument's type is determined by the generic parameter

One of my functions calls an API and accepts a parameter to limit the fields returned by the API: type MaximumApiResponse = { fieldA: string, fieldB: number } const f = async <U extends keyof MaximumApiResponse>( entity: number, prop ...

converting blob to base64 in javascript

I need assistance with decoding a blob object to a base64 string using JavaScript. Here is the code I am working with: var reader = new FileReader(); reader.addEventListener("loadend", function () { // Accessing contents of blob as a typed array ...

Styling checkboxes within a table cell in Bootstrap using CSS: Tips and Tricks

When using labels and spans with Bootstrap 4, the alignment may not appear centered when placed in a table within tr and td. How can I ensure that it is aligned properly? span.bigcheck { font-family: sans-serif; font-weight: 500; font-s ...

PHP programming language for opening, editing, and saving HTML files

Trying to use PHP to open an HTML file, remove the content of a specific div (class Areas), and then save it. $dom = new DOMDocument; $dom->loadHTMLFile( "temp/page".$y.".xhtml" ); $xpath = new DOMXPath( $dom ); $pDivs = $xpath->query(".//div[@class ...

Tips for incorporating an element in Thymeleaf only if it is not currently being displayed

Our Angular application can be hosted using either Spring Boot or "ng serve" (mainly for development purposes). When served through Spring Boot, the index.html is generated with Thymeleaf, while it is not when using "ng serve". Now, I must add a <scrip ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Is it possible to apply a personalized scrollbar design to the Autocomplete Listbox component in Mui?

I am struggling to implement a custom scroll style in Autocomplete Listbox. https://i.sstatic.net/MifSm.png After multiple attempts and thorough research, I have been unsuccessful in achieving the desired result. Here is my most recent code: <Aut ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

Is there a way to efficiently pull specific time-related data from XML API forecasts using PHP and present them in HTML tables?

Currently, I'm facing a bit of confusion on how to obtain a forecast for the upcoming 5 days of a specific city using OpenWeather's forecast api. The challenge lies in the fact that the forecasts are provided in 3-hour intervals, but I only requi ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

What can I do to correct my line breaks that are not functioning properly?

When attempting to craft a 3-paragraph div with line breaks and fixed dimensions, an unexpected outcome occurs... What I wanted: (First paragraph) (Second paragraph) (Third paragraph) Reality: [large empty space](First paragraph) (Second paragraph) ...