1

In my particular case I am using Angular and Firebase Firestore, however, the question might also be relevant to Typescript and pure Javascript.

My application is solely depending on data I am fetching from Firestore. A minimum, reproducible example of code I would produce looks like this.

TS:

export class EditStudentComponent implements OnInit {

  user:Object = {};

  ngOnInit() {
      this.NgProgress.start()
      this.fb.user$.subscribe(user => {
        this.user = user;
      })
  }
}

HTML:

User-Info:
Name: {{ user.name }}<br>
Age: {{ user.age }}<br>

In this scenario, a non existing property name or age would throw an error. Is there a better way than doing something like this for every property?

export class EditStudentComponent implements OnInit {

  user:Object = {};

  ngOnInit() {
      this.NgProgress.start()
      this.fb.user$.subscribe(user => {
        this.user = user;

        //Setting default values for all properties individually
        this.user.name = 'name' in this.user ? (this.user as any).name : 'No value found';
        this.user.age = 'age' in this.user ? (this.user as any).age : 'No value found';
      })
  }
}
dmuensterer
  • 1,875
  • 11
  • 26
  • 1
    I would do it in the HTML: `{{ user.name || "N/A" }}`. That way, the situation can be handled down the line in the proper context. If you're using the object in some sort of API call, for example, then having "No value found" in the "name" property would probably not be what you'd want. – Pointy Nov 17 '19 at 14:24
  • 1
    You could just set up a `user` object with those default values, then merge it with the `user` you get back from your subscription. – Heretic Monkey Nov 17 '19 at 14:25
  • in the html you can use like this: Name: {{ user?.name }}
    Age: {{ user?.age }}
    – Sundeep Nov 17 '19 at 15:14

1 Answers1

1

There are multiple solutions for your case where you don't need additional ts code for each attribute.

Use a question mark ? in front of an attribute to check if it exists, then the output will be just blank.

{{ user?.name }}

For nested attributes its the same.

{{ user?.name?.first }}

Use or operator ||, then you can decide what will be your default value.

{{ user?.name || 'Default name' }}

Or you write a pipe what would be an overkill and kind of the same as the second solution.

Norbert Bartko
  • 2,468
  • 1
  • 17
  • 36