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

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Encountering a 404 error when attempting to use the jQuery .load() function with parameters that include periods ('.')

I am attempting to invoke a controller function using the .load() method, but encountering an error which might be caused by the encoding of '.'. The call I am making is as follows: $("#main-content").load( url + "/" + encodeURIComponent(text ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Manipulating Hyperlinks outside the Angular JS applicationIn certain cases, Angular JS

This is my first attempt at creating a single page app. The app's content is contained within the page like a widget, functioning similar to pagination. In the header, I have links that are not related to the angular app. The link structure looks lik ...

Reduce the combined character value of the title and excerpt by trimming the excess characters

I am seeking a solution to trim the total character count of a post title and excerpt combined. Currently, I can individually adjust the excerpt through theme settings and the post title using JavaScript. However, due to varying title lengths, the height ...

Deploying Initial Node+Express+Angular Application in Production

Embarking on my first endeavor to develop a Node.js Express app with Angular 7 for deployment in production has me pondering the following: What is the recommended folder structure for this project? Should I maintain separate projects for Node and An ...

Ways to transfer a jQuery variable value to a PHP variable

I am trying to transfer a jQuery variable value to a PHP variable on the same page using AJAX in my JavaScript code. I have attempted to print the PHP variable but encountered an error. Any assistance would be greatly appreciated. <script type="text/ ...

Ways to refresh a canvas element without requiring a full page reload

My goal is to restart a canvas on a website without reloading the page, making the restart dynamic. However, I've noticed that after multiple restarts, the animation slows down and memory usage increases. The situation is complicated by my use of Met ...

What is the most effective method of testing with jest to verify that a TypeScript Enum list contains all the expected string values?

Recently, I created a list of enums: export enum Hobbies { Paint = 'PAINT', Run = 'RUN', Bike = 'BIKE', Dance = 'DANCE' } My goal is to iterate through this list using Jest and verify that all the string ...

Tips for handling various HTTP requests until a response is received

For my application, I have a need to make multiple http calls before proceeding to create certain objects. Only after all the http requests have received responses from the servers can I process the results and construct my page. To handle this scenario, ...

Why isn't the router returning JSON data?

Why am I not receiving a response from this code? const express = require('express') const mongoose = require('mongoose') const authRouter = require('./authRouter') //importing the router const PORT = process.env.PORT || 3000 ...

Using an expression from the parent controller to disable an item in an AngularJS directive

I created a list of custom directive items, each with a remove button. The issue I'm facing is that I want to disable the remove button when there's only one item left in the list, but it's not working as expected. To see this problem in ac ...

Troubleshooting Karma: Dealing with layout issues in Angular 6 and jQuery

Currently, I am implementing a workaround using JQuery to fix a visual bug in a library that I am working with. Everything was going smoothly until I started preparing for a tested version and encountered an error. Within my component, the code looks like ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

What could be causing my TypeScript object to appear as "undefined" when I try to log it?

I created a StackBlitz demo featuring a button that, when clicked, should pass a value to the controller. In the controller, there is a function designed to assign this value to an object. However, TypeScript seems to be indicating that the object is undef ...

Guide on generating angular <popover-content> programmatically

My goal is to generate angular elements dynamically. While static creation works perfectly fine, I am facing challenges when trying to create them dynamically using data. For instance: <div> <popover-content #pop1 title=" ...

Closures are like the "use" keyword in PHP or the capture list in C++, but they play a similar role in JavaScript and other transpiler languages

PHP has a useful feature with the use keyword, which allows for the usage of 'external' variables in closures. For example: $tax = 10; $totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use' return ($price * $quan ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

Apollo's MockedProvider failing to provide the correct data as expected

I created a function called useDecider that utilizes apollo's useQuery method. Here is the code: useDecider: import { useState } from 'react'; import { useQuery, gql } from '@apollo/client'; export const GET_DECIDER = gql` quer ...