I'm curious if there is a method to capture an event from Directive once the form has been reset

Is there a way to detect when the form is reset using a custom Directive in Angular?

I am working with a form that has the following structure:

<form [formGroup]="myForm" (ngSubmit)="onFormSubmit($event)">
  <input type="text" formControlName="firstName" myDirective/>
  <button id="btnClear" (click)="onReset($event)">Clear</button>
</form>

My Component:

@Component({
 selector: 'app-form',
 templateUrl: './app-form.component.html',
 styleUrls: ['./app-form.component.scss']
})
export class AppSearchFormComponent implements OnInit {

 myForm: FormGroup;

 constructor(private _fb: FormBuilder, private store: Store<any>) { }

 ngOnInit() {
 this.createForm();
 }

 createForm(){
     this.myForm = this._fb.group({
     'firstName': ['', [Validators.minLength(2)]]
  });
 }

 onReset(evt) {
 this.myForm.reset();
 }
}

Custom Directive Implementation:

@Directive({
 selector: '[myDirective]'
})
export class CustomDirective {

 constructor(private el: ElementRef, private control : NgControl) { }

 @HostListener('someEvent',['$event'])
  onkeyup(event:any){

   console.log('The form has been reset!); // Displaying this message
 }
}

Answer №1

Learn how to utilize the NgControl

Discover the base class that all control FormControl-based directives extend, binding a FormControl object to a DOM element.

Start by injecting NgControl in the directive constructor, then leverage the valuechanges method to subscribe to any changes

import { Directive} from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
  selector: '[reset]',
})
export class ResetDirective {
  constructor(private ngControl: NgControl) { }
  ngOnInit() {
    const reset$ = this.ngControl.control.valueChanges;
    reset$.subscribe((e) => {
      if (e === null) {
        console.log('Yes Form has been reset!');
      }
    });
  }
}

Check out an example here:https://stackblitz.com/edit/reset-directive

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

Setting the TypeScript version while initializing CDK

When creating a new CDK app in typescript, I typically use the following command: npx --yes <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9babdb299e8f7e8eae1f7eb">[email protected]</a> init app --language typesc ...

Trouble arises when attempting to modify a property inherited from a parent class in TypeScript while

I've defined a base class like the following: import Vue from "vue"; class ComponentBase extends Vue { constructor() { super(); this.left = 100; this.top = 100; this.isSelected = false; } public left: numb ...

When posting on social platforms, the URL fails to display any metadata

We recently completed a project (Web Application) using React .net core with client-side rendering in React. One challenge we encountered was that when the app loads in the browser, it only displays the static HTML initially without the dynamic meta tags. ...

Creating and utilizing multi-module NPM packages written in Typescript: A comprehensive guide

For a while now, I've been quite at ease creating and utilizing NPM packages with Typescript. However, these packages have typically been provided and consumed as a single module. Now, I'm interested in publishing packages that contain more than ...

TS fails to recognize any additional properties added to the constant object

When working on a function that should return an object with properties 'a' and 'b', I am defining the object first and then adding values to it later: const result = {}; result.a = 1; result.b = 2; return result; However, TypeScript i ...

Utilizing Typescript with tfjs-node to effectively integrate the node-gpu version with regular node functionalities

I am facing challenges while running my Tensorflow.js node application with and without the GPU library. In vanilla JavaScript, examples show using require() for either @tensorflow/tfjs-node or @tensorflow/tfjs-node-gpu. However, in my TypeScript setup, I ...

Regular expression for textarea validation

I'm currently working on creating a regex for a textarea in my Angular 8 application. The goal is to allow all characters but not permit an empty character at the start. I've experimented with 3 different regex patterns, each presenting its own s ...

The value of 'useFonts' cannot be changed as it is a read-only property in expo-fonts

Struggling with 'useFonts' being read-only and unable to assign In my Expo project using React Native (TypeScript), I encounter the issue of trying to import a .ttf font file. My attempt was to create a custom hook called "useFont" to pre-load ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

What are some ways to incorporate advanced/nested type variables when using arrow functions?

Is there a way to use "advanced/nested" type variables, similar to how T is utilized in this function declaration, when working with arrow functions? function wrapInObject<T>(key: string) { return (x: T) => ({ [key]: x }); } I attempted to ach ...

A clever approach to toggling the visibility of elements in Angular2 using complex conditions

My webpage includes 10-12 buttons and a few other input fields. Depending on user roles and types, I need to control the visibility of these buttons and inputs. For instance: If user type = a, then hide 3 buttons and 2 inputs. If user type = b, and user ...

Looking for Protractor CSS functionalities nodes

I tried the code below but am having trouble locating the "Login" text using Protractor: <div _ngcontent-c2="" class="align-center"> <img _ngcontent-c2="" alt="Autoprax" class="ap-logo" src="/images/apLogoSmall.svg" style="width: 100%"> ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

How to assign a value to a component variable using props in Vue.js

I am attempting to assign a props value to my component variable. Below is the code I'm working with: export default { props: { // eslint-disable-next-line vue/require-default-prop multiPaginatedTableTitle: { type: Stri ...

Understanding the process of retrieving form data files sent from Angular to TYPO3/PHP via a Post request

I've been working on uploading an image from Angular to the TYPO3 backend, but I'm struggling to read the request body in the Controller. Here's the code snippet from my Angular side: HTML: <input multiple type="file" (change ...

Execute a function in the background, even if the browser has been shut down

Is it possible to run a JavaScript function in the background, even after the user has closed the browser? I know this can be achieved in android apps, but I'm not sure about JavaScript. ...

Redirect user to the "Confirm Logout" page in Keycloak after refreshing the page before logging out

While working on a project with keycloak, I've encountered an issue that I can't seem to figure out. After logging in and navigating to my project's page, everything operates smoothly. However, if I happen to refresh the page before logging ...

Encountering the "ERROR TypeError: Cannot read property 'id' of undefined" with Angular 4 FormArray

I have a specific requirement where checkboxes need to be added dynamically on my page. Currently, I am utilizing the Angular Reactive Forms method. The browser console displays the following error, even though the checkboxes are successfully added afterwa ...

Comparing between bootstrap-flex, bootstrap-grid, and bootstrap-reboot: similarities and distinctions

The latest iteration of Bootstrap (current version as of the time this question was posed is <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6964647f787f796a7a45f757b757b766a776f762b606">[email protected]</a>) in ...

Oops! We encountered an issue: Control not found for path: 'stocks -> stockName'

Hello, I am encountering an issue while attempting to create a dynamic form using the reactive form module. Here is the HTML code I have written: <div class="container-fluid"> <h2>Stock Rebalancer</h2> <div class="form-group"> ...