Automatically adjust the model input (Signal) based on the parent and respond to any alterations in the children

Within my Angular 16 application, I have a parent component that passes a plain JavaScript object (myObj) to a child component, where it is treated as a model<MyObj>.

<!-- parent.component.html -->
  <app-children [myObjModel]="myObj"
                (myObjModelChange)="doSomething($event)">
  </app-children>

In the child component, I handle myObj as a model input:

export class ChildrenComponent {
  myObjModel = model<MyObj>();

  onMyModelChange(event: MyObj) {
    this.myObjModel.set(event);
    doThings(event)
  }

  doThings(event: MyObj) {
    console.log("I changed value in: " + event);  
  }
}

Everything works well when I modify the value in my children component, triggering the doThings() function. But what if I want the children component to react when the value changes programmatically from the parent component? For example, loading a configuration in the parent and passing myObj to the children should trigger a function.

Currently, changing myObj in the father component does not call the doThings() function, even when subscribing to changes of myObjModel using the .subscribe() API.

  constructor() {
    this.myObjModel.subscribe((val) => {
      doThings(val);
    });
  }

I prefer not to convert the model to an input because I want to take advantage of the two-way binding mechanism.

Answer №1

Utilize the effect() function for managing model inputs. According to the details provided in the documentation:

In all other aspects, treating model inputs mirrors the usage of standard inputs. Retrieve the value by invoking the signal function, even within reactive contexts such as computed and effect.

Experiment with the following code:

child.component.ts

export class Child {
  public myObjModel = model<MyObj>();

  constructor() {
    effect(() => {
      const myObj = this.myObjModel();
      console.log('Observed change in this.myObjModel within effect()');
      if (myObj) {
        this.performActions(myObj);
      }
    });
  }

  onMyModelChange(event: MyObj) {
    this.myObjModel.set(event);
  }

  performActions(myObj: MyObj) {
    console.log('Modified value in: ', myObj);
  }
}

Check out a live example here: Stackblitz

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

Link a template to a formly field when clicking on another field within an Angular formly form

Recently, I have been utilizing a Formly form that includes a section for displaying dynamic HTML content. Within this form, I am using the template field to initialize some HTML content when the page loads. However, I have encountered an issue where chang ...

Angular Error: "Provider's ngAfterViewInit method is not defined at callProviderLifecycles"

I encountered an error: evt = TypeError: provider.ngAfterViewInit is not a function at callProviderLifecycles while working on my Angular project. What's strange is that I do not have an ngAfterViewInit method, nor do I have the corresponding impl ...

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Having trouble getting POST requests to work in Angular 8 for unknown reasons

Hey there! I'm currently experimenting with using POST requests to an API in Angular for the first time, but unfortunately it's not working as expected. I've checked out some other examples of code and everything seems fine. Here is a snipp ...

What is the best way to centralize JSDoc typedef information for easy sharing between different projects?

Currently, I am incorporating @typedef JSDoc comments at the beginning of my Javascript files to define types (primarily to access certain benefits of TypeScript without fully diving into it right now). I'm curious, where can I keep JSDoc typedef inf ...

Differences between RxJs Observable<string> and Observable<string[]>

I'm struggling to grasp the concept of RxJS Observables, even though I have utilized the observable pattern in various scenarios in my life. Below is a snippet of code that showcases my confusion: const observable: Observable<Response> = cr ...

The Angular HTML Autocomplete feature is not functioning as intended when hosted on a CDN in Chrome, despite setting it to "nope" or "off"

When setting Autocomplete to "nope" or "off" in my input box for surname, I'm still able to select from the autocomplete list. This issue occurs when accessing our Ui app through CDN at link [https:// Xyz. net], but works correctly when accessing it d ...

How can I efficiently create an editForm in Angular?

Within my database, there are numerous users, each with their own collection of recipes. Each recipe contains various properties and a list of ingredients. Take a look at the screenshot below: Recipe with all properties When a user goes to edit a recipe ...

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

The information from the data source is not getting filled in

I recently started working with Angular (Version 14.2.10) and I am trying to make a REST call to populate data in the UI. However, only the header is displayed without any data showing up. I suspect there is a minor issue that I can't seem to pinpoint ...

The Excel Match function is experiencing issues when used in conjunction with the MS-Graph API

Recently, I've encountered an issue with sending a match-function post request to an Excel workbook using the MS-Graph API. Instead of receiving the value of the first column that contains the lookup value, I'm getting the value from the second c ...

Angular: Connecting template data to different visual presentations

Looking for a solution to display data and map values to another presentation without needing complex ngIf statements or creating multiple components. Check out this sample: https://stackblitz.com/edit/angular-9l1vff The 'vals' variable contain ...

I find myself hindered by TypeScript when trying to specify the accurate constraints for getUserMedia

I'm having difficulty getting a screen to stream within my Angular 5 Electron application. I am utilizing the desktopCapturer feature provided by Electron. Below is an excerpt of my code: loadCurrentScreensource() { desktopCapturer.getSources({ ...

Creating a Custom 404 Page with No Navigation Bar

Currently, I am focused on routing and navigation in my project. However, I have encountered an issue regarding how to display the 404 page without including the navigation bar and page title. Here is a snippet of my code from app.component.html: <h2&g ...

Choosing between Angular's Observable and Subject as a DataSourceWhen it comes

I am currently working on an Angular 7 application that utilizes Mat Tables to retrieve data from an API. I have implemented dynamic pagination values, where the pageSizeOptions value changes based on a dropdown selection when loading the grid. By default, ...

Can dynamic string types be declared in Typescript?

Let's consider the following scenario: export enum EEnv { devint, qa1 }; export type TEnv = keyof typeof EEnv; export const env:Record<TEnv, {something:number}> = { devint: { something: 1, }, qa1: { something: 1, }, } Now, I ai ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Guide on uploading an image to Azure Blob Storage using v10 SDK

Currently, I am attempting to upload an image to the Blob Storage in Microsoft Azure using SDK V10 within an Angular framework. The code snippet below demonstrates how I establish a connection to the Storage and retrieve the names of all containers: // E ...

Getting response headers in Angular by utilizing an HTTP interceptor

Seeking guidance on how to interpret response headers when utilizing httpinteceptor in Angular. I have exposed all the tokens in my Node.js application, but am facing challenges in comprehending all the keys passed in the response headers. intercept(req: ...

TypeScript: "The type is generic and can only be accessed for reading." - Error code 2862

Consider this sample JS function that requires type annotations: const remap = (obj) => { const mapped = {}; Object.keys(obj).forEach((key) => { mapped[key] = !!key; }); return mapped; }; I am attempting to add types using generics (in ...