angular 12 Deactive Guard with interface implentations have error with form

Viewed 32

I try to implement CanDeactive Guard with interface IFormGuard, but i get error on guard file (line: if(component.form.dirty){), that form is does not exist in interface IFormGuard. I want to implement guard for all components with forms, but don't know what to do.

This is guard file:

import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { FormGuardDialogComponent } from 'src/app/views/helpers/form-guard-dialog/form-guard-dialog.component';
import { IFormGuard } from '../interfaces/i-form-guard.interface';

@Injectable({
  providedIn: 'root'
})
export class FormGuard implements CanDeactivate<IFormGuard> {
  constructor(private dialog: MatDialog){}
  canDeactivate(
    component: IFormGuard,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if(component.form.dirty){
      const dialogReference = this.dialog.open(FormGuardDialogComponent);
      return dialogReference.afterClosed()
    }
    return true;
  } 
}

This is interface:

export interface IFormGuard{
    isFormDirty(): boolean;
}

This is implementation guard in component:

import { Component} from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { first } from 'rxjs/operators';
import { IFormGuard } from 'src/app/guard/interfaces/i-form-guard.interface';
import { CategoryModel } from 'src/app/models/categories/category-models';
import { CategoryService } from 'src/app/services/category/category.service';
import { UserService } from 'src/app/services/user/user.service';

@Component({
  selector: 'app-new-category',
  templateUrl: './new-category.component.html',
  styleUrls: ['./new-category.component.css']
})
export class NewCategoryComponent implements IFormGuard{
  

  newCategory: CategoryModel = new CategoryModel();
  form: FormGroup;
  categoryName: FormControl;
  userId: string | any = '';

  constructor(
    private categoryService: CategoryService,
    private userService: UserService,
    private toastr: ToastrService,
    private formBuilder: FormBuilder,
    private router: Router) {
      this.categoryName = new FormControl('');

      this.form = this.formBuilder.group({
        categoryName: this.categoryName
      });
    }

  isFormDirty(): boolean {
    return !this.form.dirty;
  }

    onSubmit(){
      this.userId = this.userService.getUserId();

      this.newCategory = {
        id: '00000000-0000-0000-0000-000000000000',
        category: this.categoryName.value,
        isBuildIn: true,
        createdAt: new Date(),
        userId: this.userId
      }

      this.categoryService
        .createCategory(this.newCategory)
        .pipe(first())
        .subscribe(res =>{
          console.log(res);
          this.toastr.success("Dodano kategoriÄ™");
          this.router.navigate(['/categories'])
        },
        error => {
          console.error(`ErrorHttp: ${JSON.stringify(error)}`);
        })
    }
}
1 Answers

just add form: Formgroup; to your IFormGuard interface.

Related