I have an angular component which should display different information depending on which button was clicked to route to it. If button 1 was clicked I want to set button1=true in component2 and use an ngIf to display the correct information. If button 2 was clicked I want to set button2=true and use an ngIf to display the correct information.
The two components have different urls and are not parent/child of each other.
The code below is a barebones example of what I am trying to achieve.
How can I communicate to component 2 whether button 1 or button 2 was pressed?
comp1.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
constructor(private router: Router,) { }
public onButton1(){
this.router.navigate(['/comp2']);
}
public onButton2(){
this.router.navigate(['/comp2']);
}
ngOnInit() {
}
}
comp1.component.html
<div>
<button (click)="onButton1()">Button1</button>
<button (click)="onButton2()">Button2</button>
</div>
comp2.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.css']
})
export class Comp2Component implements OnInit {
public button1 = false;
public button2 = false;
constructor() { }
ngOnInit() {
// if button pressed == "button1" in component 1
this.button1 = true
// if button pressed == "button2" in component 1
this.button2 = true
}
}
comp2.component.html
<div *ngIf="button1">
Button 1 was clicked
</div>
<div *ngIf="button2">
Button 2 was clicked
</div>
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Comp1Component } from './comp1/comp1.component';
import { Comp2Component } from './comp2/comp2.component';
const routes: Routes = [
{ path: 'comp1', component: Comp1Component },
{ path: 'comp2', component: Comp2Component }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<router-outlet></router-outlet>