Angular 5 - Stop errors from undefined object before loading data
Multiple ways: You can use any one suitable to you.
1. Adding ngIf : If name
is undefined
or null
or ''
it will not render the element and prevent errors in console. When name
gets defined value it will automatically update the view.
*ngIf="name"
2. Adding async pipe : View will update whenever name
gets defined. It waits for name
to get defined (or resolved). (name should be a promise or an observable for this to work.)
{{ name | async }}
3. Adding fallback value : This is simply or
condition. If name
is undefined
or null
or ''
, you can decide which fallback value to assign .
{{ name || "" }}
As mentioned in previous responses you can use {{ name | async }}
but remember if you want to use {{ name | async }}
, name must be a promise or an observable.
Otherwise you'll get an error like this :
ERROR Error: InvalidPipeArgument: 'xxx' for pipe 'AsyncPipe'
Just initialize your variable
name : string = "";
or you can do it inside of the constructor
this.name = "";