Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'title' of undefined, but title is displayed

Tags:

angular

I'm new with angular 4 , and I'm trying to build my first application.

The title is displayed in the screen but get this error in the console :

enter image description here

This is line 26 in the html file:

<h1>{{result.title}}</h1>

This is TravelDetailComponent:

export class TravelDetailComponent implements OnInit {

result: string[];
id: number;

constructor(private http: Http, private globals: Globals, private activatedRoute: ActivatedRoute) {
}


ngOnInit() {
  this.activatedRoute.params.subscribe((params: Params) => {
      this.id = params['id'];
      console.log(this.id);
  });
  this.http.get(this.globals.baseUrl + 'travels/' + this.id)
      .map(res => res.json()).subscribe(result => this.result = 
result);
}

}

why the title is displayed in the screen but I get this error in the console and how can I solve it ?

like image 264
hous Avatar asked Dec 05 '22 13:12

hous


2 Answers

You'll run into this A TON in angular unless you familiarize yourself with the Angular Template Syntax. Specifically the use of the *ngIf and the elvis operator ?.

For example, if you are just wanting to display the title you could do the following to make sure the page doesn't try to render the title until it has one.

<h1 *ngIf="title">{{ title }}</h1>

Furthermore if you have an object with a property you can forgo the *ngIf and check to make sure the object has resolved. For instance let's say you save all of the page's data into the page object and like above, want to display the title.

<h1>{{ page?.title }}</h1>

If you wanted to be really safe, you could still wrap it in an *ngIf statement that checks the title specifically, but usually if you have data within the page object, it's safe to assume there's a title in there.

like image 153
joshrathke Avatar answered Jan 05 '23 00:01

joshrathke


You need to add safe operator in HTML to check if the value is present, this will avoid the above error if the value is not present

<h1>{{ yourObj?.title }}</h1>
like image 45
Sajeetharan Avatar answered Jan 04 '23 23:01

Sajeetharan