Click here to Skip to main content
15,888,320 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I have a piece of code which emits and binds a 'Post' abject between three components(PostList, App, PostEdit). Now I want to use routing such that PostList and PostEdit should have different navigations. Kindly help me how to use events using <router-outlet> in angular 7.

Here is my emitted event :

JavaScript
<pre>@Output() emittedPost = new EventEmitter<Post>();
 onFetchPost(id : string){
    const fetchedPost : Post = this.postsService.fetchPost(id)[0];
    console.log("Fetched Post",fetchedPost);
    this.emittedPost.emit(fetchedPost);
  }


Getting post in app.component.html :
HTML
<pre><app-header></app-header>
<main>
    <!-- <router-outlet></router-outlet> -->
    <app-post-create [receivedPost]="receivedPost"></app-post-create>
    <app-post-list (emittedPost)="onRecivePost($event)"></app-post-list>
</main>


app.component.ts:
JavaScript
export class AppComponent {
  receivedPost : Post;
  onRecivePost(post : Post){
      console.log("Received Post in app component",post); 
      this.receivedPost = post;
  } 
}

Binding in PostList Component
JavaScript
@Input() receivedPost: Post;
    ngOnChanges(){
    try{
      if (this.receivedPost !== null){
        this.enteredTitle = this.receivedPost.title;
        this.enteredContent = this.receivedPost.content;
        console.log("Received Post in edit component",this.receivedPost);
      }
    } catch{
      console.log("No Posts");
    }

When I am clicking on edit posts were being passed among components. But, what I need is to enable that <router-outlet> in app.component.html so that the PostList and PostEdit should come on different navigations. So, kindly suggest me on how to use <router-outlet> along with event emmitting
Here is my app-routing.module.ts:
JavaScript
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";

import { PostListComponent } from "./posts/posts-list/post-list.component";
import { PostCreateComponent } from "./posts/posts-create/post-create.component";

const routes: Routes = [
  { path: '', component: PostListComponent },
  { path: 'create', component: PostCreateComponent },
  { path: 'edit', component: PostCreateComponent}
];

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


What I have tried:

I tried making
<router-outlet></router-outlet>
to
<router-outlet (emittedPost)="onRecivePost($event)"></router-outlet>


But, that doesn't even seem to be helping.

Thanks in advance
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900