When the child component's form is marked as dirty, the parent component can access it

I have implemented a feature in my application that notifies users about pending changes on a form before they navigate away.

Everything works as expected, but I have a child component with its own form that needs to be accessed by the guard to check if it has unsaved changes.

How can I access this child component's form within the guard logic?

Guard:

import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { DialogService } from "ng2-bootstrap-modal";
import { ConfirmComponent } from '../components/confirm/confirm.component';
import { Inject } from '@angular/core';

export interface FormComponent {
    form: FormGroup;
}

export class PreventUnsavedChangesGuard implements CanDeactivate<FormComponent> {

constructor(@Inject(DialogService) private dialogService: DialogService) { }

canDeactivate(component: FormComponent): Promise<boolean> {

    if (component.form.dirty) {
        return new Promise<boolean>((resolve, reject) => {

            this.dialogService.addDialog(ConfirmComponent, {
                title: 'Unsaved Changes',
                message: 'You have unsaved changes. Are you sure you want to navigate away?'
            })
                .subscribe((isConfirmed) => {
                    return resolve(isConfirmed);
                });
        });
    }

    return Promise.resolve(true);
    }
}

Answer №1

Transfer the parent form as a parameter to the child component for seamless integration. The child component is responsible for linking its input fields with the parent form. If any changes are made to the child's input fields, it will automatically reflect on the parent form. This eliminates the need to directly manipulate the child form in your guard logic. Here is an example:

Parent Component TypeScript

import {FormBuilder, FormGroup} from "@angular/forms";
private parentComponentForm: FormGroup;
export class ParentComponent implements OnInit, OnDestroy {

    constructor(private _fb: FormBuilder) {}

    ngOnInit() {
        this.parentComponentForm = this._fb.group({});
    }
}

Parent Component HTML

<child-component
   [parentForm]="parentComponentForm"
</child-component>

Child Component TypeScript

export class ChildComponent implements OnInit {
   @Input() parentForm: FormGroup;      
   let inputFieldControl = new FormControl('', Validators.required);
   this.parentForm.addControl(this.inputFieldControlName, inputFieldControl);
}

Child Component HTML

<input type="text" class="form-control" [formControl]="parentForm.controls[inputFieldControlName]">

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

What is the best way to incorporate CDN into my webpack build process?

I have developed a module with the following code: export default () => console.log('hello my_module~!') The configuration in the webpack.config.js file looks like this: module.exports = { // ... output: { // ... library: 'he ...

Playing with background hues

Can anyone help me with this issue? I've been attempting to change the background color using jQuery upon document load, but it doesn't seem to be working. Any thoughts on what I might be doing wrong? http://jsfiddle.net/KczZd/2/ HTML: <d ...

Iterate through a JavaScript array to access objects with varying IDs

Struggling to navigate the JSON data due to ID 29450 and 3000 out of a total of 1500 IDs in the database. Looking to log the information ['Id', 'Description', 'StartDate'] for both IDs. Feeling a bit stuck, hoping someone can ...

Tips for positioning the overlay to match the icon list when hovering- JavaScript/Cascading Style Sheets (CSS)

My challenge involves a list of <li>'s accompanied by an icon that, when hovered over, displays an overlay containing information about the 'test'. The setup looks something like this: test1 test2 test3 and so forth.... Here' ...

Real-time chart updates through REST API integration with JavaScript

I am searching for a JavaScript library that is capable of creating line charts and making calls to a REST API every few seconds (such as 5s or 3s) in order to update the line chart dynamically. I have found some libraries that support live chart updatin ...

Looking for assistance with arranging and managing several containers, buttons, and modals?

My goal is to create a grid of photos that, when hovered over, display a button that can be clicked to open a modal. I initially got one photo to work with this functionality, but as I added more photos and buttons, I encountered an issue where the first b ...

Guy discussing the ins and outs of JavaScript variables

I am facing an issue with retrieving the value in the jQuery script. The value should be taken from route_path_images, but it's not showing up. var route_path_images="http://www.domain.com" jQuery("#header_background_night_star").fadeIn(2000).css("b ...

AngularJS modules are not loading dependencies such as constants or controllers

While searching for the reason why a properly defined factory is not loading, I came across this question. This led me to contemplate on the concept of services being "defined in an angular module". Consider this example: angular.module('d3', ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Utilizing a monorepo approach enables the inclusion of all *.d.ts files

Scenario: In our monorepo, we have 2 workspaces: foo and bar. foo contains the following files: src/file.ts src/@types/baz.d.ts The bar workspace is importing @monorepo/foo/src/file. While type-checking works for the foo workspace, it does not work fo ...

Is there a way for a dialog to prompt a Parent Window to refresh its grid?

My Angular Material Grid has an Edit option that opens a form using mat-dialog when clicked. Upon trying to close the form, another dialog prompts the user to save the changes made. If the user chooses to save, the data is sent to the backend via API and b ...

Managing the automatic download of a zip file through JQuery - A guide

When working with a REST API and creating a zip file for forced download, the task is to call the API by sending necessary POST data through JQuery to initiate the download. How can this goal be accomplished effectively? ...

Using *ngIf in Angular to display a list of items only when the length is greater than 0

<h1>{{title}}</h1> <ul> <li *ngFor="let breed of data.message | keyvalue"> <a [routerLink]="['/picsofbreed']" [queryParams]="{breed: breed.key}" target="_blank">{{breed.k ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Is it possible to request a GET on a server's JSON file using a specific key?

I am currently working on a project involving an auto-suggestion exercise using a JSON file located on a server. I'm not entirely clear on the web development terminology, so one requirement has me a bit confused: The requirement states: "On the keyu ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

Tips for connecting Vue data to a dropdown menu

While diving into Vue.js, I'm encountering a puzzling issue. Despite receiving data from the server (5 records), it's not populating the <select> element properly. Instead of multiple options, all I see is a single one displaying {{dept.DNa ...

What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response: {username:'patrick',userid:'3636363',position:'employee'} {username:'patrick',userid:'3636363',position:&a ...

Unveiling the Mysteries of HTTP Headers in Angular

Seeking a way to retrieve a token set in the http header within my Angular application. This is how my Angular application is being served: var express = require('express'); var app = express(); var port = process.env.PORT || 3000; var router = ...