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.