Angular router

Routes:


export const POST_EDIT_ROUTE: Routes = [

  {

    path: 'edit',

    component: PostEditComponent,

    data: {

      dataMode: 'EDIT'

    }

  },

  {

    path: 'delete',

    component: PostEditComponent,

    data: {

      dataMode: 'DELETE'

    }

  }

];

PostEditComponent sample:


import { Component, OnInit } from '@angular/core';

import { FormControl, FormGroup, Validators } from '@angular/forms';

import { ActivatedRoute } from '@angular/router';



import { PostInterface } from '@core/interfaces/post.interface';

import { PostService } from '@core/services/post.service';





@Component({

  selector: 'app-post-edit',

  templateUrl: './post-edit.component.html',

  styleUrls: ['./post-edit.component.scss']

})

export class PostEditComponent implements OnInit {

  postForm: FormGroup;

  postData: PostInterface;

  postId: number;



  constructor(private activatedRoute: ActivatedRoute,

              public postService: PostService) {

    this.postId = +this.activatedRoute.snapshot.paramMap.get('id');



    // Get data param from the route config

    console.log(this.activatedRoute.snapshot.data?.dataMode);



    // will console.log if URL will look like: site.com/post/2/edit?action=create

    if (this.activatedRoute.snapshot.queryParamMap.get('action') === 'create') {

      console.log('Created successfully');

    }

  }



  ngOnInit(): void {

    this.postForm = new FormGroup({

      title: new FormControl('', [Validators.required]),

      content: new FormControl('', [Validators.required])

    });



    // populate post form data

    this.postService.getById(this.postId).subscribe((postResponse: PostInterface) => {

	  this.postData = postResponse;

      const postValues = {

        title: this.postData?.title,

        content: this.postData?.content

      };

      this.postForm.patchValue(postValues);

    });



  }



  submit() {

    const postFormData = {

      title: this.postForm.value.title,

      content: this.postForm.value.content

    };

    this.postService.update(this.postData.id, postFormData).subscribe(postResponse => {

      console.log('Updated successfully');

    });

  }



}

Leave a Comment