Angular 4's ngOnChanges method does not display the updates made

I've been attempting to utilize ngOnChanges in Angular 4, but I haven't been able to get it to work.

login.component.ts

    import { AuthService } from './../../services/auth.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit, OnChanges,SimpleChanges } from '@angular/core';
import { FormControl, Validators, FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit,OnChanges {
    returnUrl: string;
    signInForm: FormGroup;
    errorMsg: any;


    constructor(
        private userService: AuthService, private router: Router, private route: ActivatedRoute, private fb: FormBuilder) {
            this.signInForm = fb.group ({
                'email' : new FormControl(null, Validators.compose([Validators.email, Validators.required])),
                'password': new FormControl(null, Validators.compose([Validators.required, Validators.minLength(6)]))
              });
         }

    login() {

        this.userService.login({email: this.signInForm.value.email, password: this.signInForm.value.password})
            .subscribe(
                data => {
                    this.router.navigate(['']);

                },
                error => {
                    this.errorMsg = error._body;
                    console.log(this.errorMsg);
                });
    }
    ngOnChanges(changes: SimpleChanges) {
        if(changes.email){
            console.log("email input change");
        }
    }

  ngOnInit() {

  }

}

login.component.html

    <form [formGroup]="signInForm" (ngSubmit)="login()">    
<div class="ui middle aligned center aligned grid">
  <div class="column">
    <h2 class="ui teal image header">
      <div class="content">
        Log-in to your account
      </div>
    </h2>
    <div class="ui large form">
      <div class="ui stacked segment">
        <div class="field">
          <div class="ui left icon input">
            <i class="user icon"></i>
            <input type="text" name="email" formControlName="email" placeholder="E-mail address">
          </div>
          <span

Upon inspection of the ngOnChanges function:

ngOnChanges(changes: SimpleChanges) {
        if(changes.email){
            console.log("email input change");
        }
    }

I'm specifically trying to monitor changes in the email input, such as user input, but no output is being displayed in the console. It seems like the change detection is not functioning as expected.

Answer №1

To handle changes in input when using a child component, you can utilize ngOnChanges. In your situation, you can simply implement (change)="onChange($event)"

 <input type="text" name="email"  [(ngModel)]="email"  (change)="onChange($event)"`** formControlName="email" placeholder="E-mail address">

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

Protractor end-to-end tests fail to run properly when the `--spec` flag is utilized

Currently, I am running 'ng e2e' on an Angular CLI project and I am looking to specify a specific test to run instead of running all of them. When I execute ' ng e2e --aot ', the test runs smoothly. However, when I try ' ng e2e ...

The property 'setParentKeyForNodeData' is not found in the 'Model' type. Perhaps you meant to use 'setCategoryForNodeData'?

As I work with gojs and utilize an organizational chart, I have encountered a problem with one of the context menus. Specifically, when selecting "Remove Role", I receive an error message stating Property 'setParentKeyForNodeData' does not exist ...

Sequelize is not giving the expected model even after utilizing `include: [{ model: this.buildModel, required: true }]`

I've hit a roadblock trying to solve this problem. Despite my belief that I've correctly handled the migration, model definition, and query, I'm unable to retrieve the build in my iteration. Below are the models: SequelizeBuildModel.ts @Ta ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...

What is the process to generate a universal error page in Angular?

I have implemented a simple example in Angular 6 using a globalErrorHandler for error cases. I have also included a loader that runs after the login operation and before loading data into a table. Everything seems to be working fine, but I have encountered ...

HTML elements are failing to display when utilizing the Angular selector

I'm currently working on a project with Angular 2/4 and I'm running into an issue with rendering the app.component.html in the main index.cshtml page. All I can see is the word "loading" that is hard-coded in the index.cshtml file. I've doub ...

Access a PDF document in a new tab and save it with a specific file name using Angular

I am facing a challenge in Angular where I want to open a PDF file in a new tab and enable the user to download it with a specific name (Example.pdf). The current code successfully downloads the PDF but does not open a new tab (target=_blank is ineffecti ...

Issue encountered during ng build using Angular 6 flag configurations

Upon attempting to build my app with specific flags, I encountered an error. When using only ng build, the process is successful. However, when adding flags such as: ng build -aot -vc -cc -dop --buildOptimize The following errors were displayed: An is ...

What is the workaround for using DomSanitizer in a unit test when the component does not automatically inject it?

I have a basic component that does not utilize the DomSanitizer. Let's call it export class ExampleComponent { @Input() public safeHtml: SafeHtml | undefined; } How can I incorporate the DomSanitizer in a unit test? I have attempted to prov ...

Leveraging Angular 6: Implementing custom scripts on a component basis and verifying their presence

I need some help with a script that I want to run on a specific component only. I've managed to add the script to the component, but there are a few issues that I'm unsure how to fix. When I go to the component, the script is added to the DOM b ...

Error in BehaviorSubject<any[]>: Unable to assign type 'any[] | null' to type 'any[]'

When I try to pass a BehaviorSubject from my CacheService to a component @Input() that expects an array, I encounter an error stating that 'any[] | Type 'any[] | null' is not assignable to type 'any[]'. This occurs even though the ...

The Angular http.post function seems to be returning null responses consistently, without any actual data being received

When making a post call in Angular using Http.post, I am sending jsonData as a parameter with the following formatted data. However, every time I receive a response as null. Could you please review my code and let me know if there are any mistakes? Here ...

Retrieve a specific JSON object by ID in an Angular Typescript observable

Below is a json string that contains both "stocks" and "contacts" data arrays. Depending on the request, I need to extract either the "stocks" or "contacts" data: [{ "id": "stocks", "name": "Stocks", "data": [ { "id": 1, "name": "Act ...

What could be causing jQuery to overlook this button?

Having some trouble with my angular, bootstrap, and jQuery setup. I can't get jQuery to select a button and trigger an alert when clicked: $('#some_button').click(function(e) { alert('testing'); }); <button id="some_but ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

Angular 2 integration for Oauth 2 popup authorization

I am in the process of updating an existing Angular application to utilize Angular 2. One challenge I am facing is opening an OAuth flow in a new pop-up window and then using window.postMessage to send a signal back to the Angular 2 app once the OAuth proc ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Binding in Angular for internationalization (i18n)

What is the best way to translate a binding using Angular's built-in i18n feature? //translating attribute works fine <mycomponent i18n-myattribute myattribute="just an attribute"></mycomponent> //how to handle translating bi ...

Tips for updating an array in TypeScript with React:

Encountering an issue while updating my state on form submission in TypeScript. I am a newcomer to TS and struggling to resolve the error. enum ServiceTypeEnum { Replace = 'replace product', Fix = 'fix product', } interface IProduc ...

Error encountered when an Angular expression is changed after it has already been checked in a dynamically generated component

I am encountering a problem with Angular and the CdkPortal/CdkPortalHost from @angular/cdk. I developed a service that allows me to associate a CdkPortalHost with a specified name and set its Component at any given time. This is how the service is struc ...