Explain to me the meaning of the `change` event in Angular 2

Can you explain the significance of the change event in Angular 2? When does it occur and how is it utilized?
For example, what action am I subscribing to in the code snippet (change)="update()"?

Link to Plunker demo

import {Component, View, Input, Output, EventEmitter, OnChanges} from '@angular/core'

@Component({
selector: 'inner-component',
template: `
<label><input type="checkbox" [(ngModel)]="data.isSelected"> Selected</label>
`
})
export class InnerComponent {
 data = { isSelected: false };
}

@Component({
 selector: 'my-app',
 template: `
<p><inner-component (change)="update()"></inner-component></p>
<p>The component was updated {{count}} times</p>
`,
directives: [InnerComponent]
})
export class AppComponent {
 count = 0;

 update() {
 ++this.count;
 }
}

PS: Same question in Russian.

Answer №1

Explaining event bubbling: change happens on an input element, then bubbles up through the DOM tree until it is handled by the inner-component element. This can be verified by logging the event:

http://example.com/some-link

@Component({
  selector: 'my-app',
  template: `
    <p><inner-component (change)="update($event)"></inner-component></p>
    <p>The component has been updated {{count}} times</p>
  `,
  directives: [InnerComponent]
})
export class AppComponent {
  count = 0;

  update($event) {
    console.log($event, $event.target, $event.currentTarget);
    ++this.count;
  }
}

Answer №2

The change event is triggered when there is a change in an input field. If your inner component is not a native Angular component, you will need to specify the event emitter yourself:

@Component({
  selector: 'inner-component',
  template: `
    <label><input type="checkbox" (change)="inputChange.emit($event)" [(ngModel)]="data.isSelected"> Selected</label>
  `
})
export class InnerComponent {
  @Output('change') inputChange = new EventEmitter();

  data = { isSelected: false };
}

In your AppComponent, you can now listen for these events:

@Component({
  selector: 'my-app',
  template: `
    <p><inner-component (change)="update($event)"></inner-component></p>
    <p>The component has been updated {{count}} times</p>
  `,
  directives: [InnerComponent]
})
export class AppComponent {
  count = 0;

  update(event: any) {
    ++this.count;
    console.log(event);
  }
}

Answer №3

This is simply an event emitter. Take Angular mat design's source code for mat-select as an example, where you can find the selectionChange.

@Output() readonly selectionChange: EventEmitter<MatSelectChange> =
      new EventEmitter<MatSelectChange>();

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

Challenges with Type Aliases when Using Typescript with MaterialUI Icons

I am searching for a way to dynamically incorporate Material UI icons into my code based on specific strings found in a configuration file. I have come across an approach that seems promising: https://medium.com/@Carmichaelize/dynamic-tag-names-in-react-a ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...

The character 'T' cannot be converted to a string

Here's the issue: I attempted to create a function that takes a parameter and returns the same type. To illustrate, I started with the most basic example: type Test = <T>(arg: T) => T; const test: Test = (arg: string) => arg; However, t ...

Have the validation state classes (such as .has-error) been removed from Bootstrap 5?

I've noticed that the validation state classes (.has-success, .has-warning, etc) seem to have been removed in bootstrap 5 as they are not working anymore and I can't find them in the bootstrap.css file. Before, I could easily use these classes w ...

Troubleshooting responsive design problems with button groups in Angular Bootstrap

Embarking on my journey in front-end development with aspirations to become a full-stack developer, I have chosen to study Jhipster, Angular, and Bootstrap. Recently, I successfully implemented a Bootswatch theme (Pulse) and proceeded to create a card lis ...

Subscribe to a new Observable once the previous one completes

I need assistance in getting the current user after logging in. When I use this.router.navigate([this.returnUrl]); it does not work. Can someone please help me identify what is wrong here and how I can fix it? onSubmit(): void { this.authService.logi ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

Selenium does not hesitate to click on an element

Salutations! I've been grappling with an issue for quite some time now. The crux of the problem lies in my desire for selenium to pause until a specific element becomes clickable following a message being displayed on the screen. The element ID in q ...

Angular 2 rc4's HTTP requests are generating uncaught exceptions (in promise)

Is there a change in Angular 2 HTTP service after upgrading to Angular 2 rc4? I have spent the entire day going through Angular HTTP client documentation and searching on Stack Overflow, but I can't seem to find the solution to my problem. Here are ...

Angular Gitlab CI/CD Pipeline Configuration with .gitlab-ci.yml

I'm new to continuous deployment with Gitlab and am trying to set up a pipeline for Angular. Everything is working smoothly except for the fact that I am unable to copy the dist folder from one location to another using the commands mentioned below. ...

Issues within the team relating to the assortment of items in the shopping cart

Working on an angular online shop and facing a challenge here. We have a list of products, but I need to single out one specific product from the list when the "add to cart" button is clicked. Currently exploring this in the product.component.ts file with ...

Having difficulty importing SVG files in TypeScript

When working with TypeScript (*.tsx) files, I encountered an issue where I couldn't import an SVG file using the following statement: import logo from './logo.svg'; The transpiler gave me this error message: [ts] cannot find module '. ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...

What is the best way to store information in JSON format and transmit it to a server using an API?

I'm looking to save the form data in JSON format and send it from my UI to the server. I've searched through numerous sources but haven't found a solution yet. Struggling with the basic design structure, any help would be greatly appreciat ...

Tips for effectively navigating through pages using routing in angular 4?

'navigation.ts' File import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; //Layouts import { MainLayoutComponent } from './layouts/main-layout.component'; //pages imp ...

Utilizing Vue and TypeScript - Retrieving a Variable Declared in the Data() Method within Another Method

I recently made the switch to using Vue3 with TypeScript after previously working with Vue2 and JavaScript. I am encountering an issue in my IDE where it is showing an error (even though the code itself functions correctly, but may not be entirely accurate ...

Tips for securely passing props based on conditions to a functional component in React

I came across this situation: const enum Tag { Friday: 'Friday', Planning: 'Planning' } type Props = { tag: Tag, // tour: (location: string) => void, // time: (date: Date) => void, } const Child: React.FC<Props> = ...

Utilizing TypeScript/React to Access Data from an Excel Spreadsheet

Hey there! I've been working on a Single-Page-Application with Typescript and React, and now I need to read data from an Excel sheet. The xlsx Library (npm) seems to be the way to go, but I'm having trouble getting it to work. Can anyone offer an ...

Issue with Component in Angular not functioning properly with proxy construct trap

Currently working with Angular 17, I have a straightforward decorator that wraps the target with Proxy and a basic Angular component: function proxyDecorator(target: any) { return new Proxy(target, { construct(target: any, argArray: any[], newTarget: ...

Retry on the "outer" observable using RxJs

My Component Store is making an API call that can sometimes result in a lengthy payload causing the response to fail due to URL length. To handle this issue, I am looking to utilize RxJs retry to retry the API call without the massive payload on the second ...