Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator.

app.component.html

<app-child [myVariable]="myVariable"></app-child>

app.component.ts

@Component(...)
export class AppComponent implements OnInit {
  // Initial value, no errors
  public myVariable = "Hello world";

  ngOnInit() {
    // Change value after 1s, no errors
    setTimeout(() => {
      try {
        this.myVariable = "Cool message";
      } catch (e) {
        console.log("Error thrown");
      }
    }, 1000);

    // Change value after 2s, error from child setter is thrown but not caught
    setTimeout(() => {
      try {
        this.myVariable = null;
      } catch (e) {
        console.log("Error thrown");
      }
    }, 2000);
  }
}

The @Input decorator has a setter that validates the passed value. If it doesn't meet the condition, an error is thrown.

child.component.ts

@Component(...)
export class ChildComponent {
  private _myVariable: string;

  @Input()
  public set myVariable(val: string) {
    console.log('Trying to set value ' + val);
    
    if (!val) {
      throw new Error("Cannot set null value");
    }

    this._myVariable = val;
  }

  public get myVariable() {
    return this._myVariable;
  }
}

Is there a way to catch the error thrown by the child @Input setter? You can find an example on StackBlitz.

Answer №1

In my understanding, achieving this may pose a challenge due to the nature of how the Input() function operates. When you assign a value in your parent component, Angular manages input changes differently.

A potential solution could involve referencing the child component in the parent component and directly setting the property that way.

To demonstrate this approach, I have made adjustments to your StackBlitz example: https://stackblitz.com/edit/angular-ivy-drncnk

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

Increase the options available in the dropdown menu by adding more selected items, without removing any already selected

I came across this code on the internet http://jsfiddle.net/bvotcode/owhq5jat/ When I select a new item, the old item is replaced by the new item. How can I add more items without replacing them when I click "dropdown list"? Thank you <select id=&qu ...

JQuery does not operate on content that is fetched through ajax requests

I've been struggling with this issue for quite some time now and I just can't seem to figure out what I'm doing wrong. (I suspect it's related to the ajax response) I attempted to upload an image to the server using the uploadifive plu ...

Troubleshooting the issue of Child redirect in Angular4 Routing not functioning

My Angular4 routing setup looks like this: {path: 'siteroot', component: SiteMessengerComponent}, { path: '', component: FrameDefaultComponent, children: [ { path: 'user/:userId', component: SiteUs ...

Tips for overlaying a webpage with several Angular components using an element for disabling user interactions

I currently have an asp.net core Angular SPA that is structured with a header menu and footer components always visible while the middle section serves as the main "page" - comprised of another angular component. What I am looking to achieve is ...

Using Angular 4 to monitor changes in two-way binding properties

Recently, I developed a unique toggle-sorting component that examines if the current sorting parameters align with its sorting slug and manages clicks to reflect any changes. // toggle-sorting.component.ts @Input() sortingSlug: string; @Input() currSorti ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...

Enhance the visual appeal of incoming data using Angular Material's dynamic styling feature

Is it possible to enhance the text with some CSS styling to make each item stand out like in this example: https://i.stack.imgur.com/kSyZE.png I prefer not to include a cross button or provide users with the option to add tags. The data is coming from a R ...

Angularjs and Angular (5) routing combo

I'm currently exploring the possibility of running angular alongside our existing angularjs application. Instead of immediately diving into the tedious process of transitioning to ngUpgrade, I wanted to attempt running them independently first. My ide ...

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...

Utilizing Windows Azure and restify for node.js Development

I have an azure website with a URL like: . In my server.js file, I have the following code: var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify ...

How to automatically choose the first option in a v-for loop in Vue.js

I have a loop that creates a dropdown menu from an array: <select class="form-control" v-model="compare_version" > <option v-for="(version, index) in allVersions" v-bind:value="index" v-bind: ...

Creating a responsive and expandable table using HTML and JavaScript

I need help with making my html table resizable in a vertical direction. The cells can overflow if there isn't enough space, so I want to allow users to stretch the table by dragging and extending the bottom edge. Can anyone provide guidance on how to ...

Leveraging Vue slots to display a component inside another component

I am currently working on creating a base modal component that can be re-used, utilizing slots to insert the modal content. The issue I am facing is that when the modal is triggered by clicking a button, it displays without any content present. How can I e ...

What methods does Angular use to display custom HTML tags in IE9/10 without causing any issues for the browser?

Exploring web components and utilizing customElements.define tends to cause issues in IE9/10. I've noticed that Angular is compatible with IE9/10, and upon inspecting the DOM tree, it seems like Angular successfully displays the custom element tags. ...

Warning: Angular Compilation Issue - Deprecation Advisory

After upgrading to Angular 13, I've been encountering this deprecation warning. TypeError: message.trim is not a function at Function.Rule.FAILURE_STRING (/home/app/node_modules/tslint/lib/rules/deprecationRule.js:30:81) at cb (/home/app/node_modules ...

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

Angular 2 setting a class property to the output

There seems to be an issue with logging to the console in my getProfile() method. When I assign this.user to user, it does not return my json object as expected. If I write the following code: getProfile() { this.userService.getPortInfo() .th ...

What is the functionality of this.$eval in Vue.js?

During the process of updating an unfamiliar old script from version 0.11 to 2.5.4, an alert popped up stating: To address the warning message saying 'Replace this.$eval('reportData | reportFilter false') with a solution using normal Java ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

How can you fetch data from a PHP file using AJAX before performing a header redirect?

I am currently in the process of adding more dynamism to my website. I have developed a forum from scratch and now I am integrating JavaScript into it. All the PHP backend work is complete. My next goal is to enable user login without having to refresh the ...