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.