How to catch an error thrown by a child component setter?

Viewed 439

I have an App component which stores a value that is passed into a Child component via an @Input decorator.

app.component.html

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

app.component.ts

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

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

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

The @Input decorator has a setter to check whenever the passed value meets a condition. If the condition is not met, an error will be 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 any way how can I catch the error thrown by the child @Input setter? Please check the StackBlitz with an example.

1 Answers

I believe this is not possible because of how Input() works. Your assignment only assigns the variable in your parent component, but angular handles the input changes differently.

One way to solve this is to reference your child in your parent component and set the property directly.

I've forked your stackblitz to use this approach: https://stackblitz.com/edit/angular-ivy-drncnk

Related