2

I am learning Angular 2 and I am stumbled in one of my views that it's weird to see.

inside my ts code I have:

import { CompanyService } from '../../services/company.service';
import { Company } from '../../models/company';    
export class TestEssayComponent implements OnInit {
        company: Company;
        constructor(private companyService: CompanyService){}
    ngOnInit() {
        this.getCompany();
      }
    getCompany(){
        var company_id: number;
        company_id = parseInt(localStorage.getItem('company_id'));
        this.companyService.getById(company_id).subscribe(
          data => {
            var company = new Company;
            company = data.data;
            this.company = company;
            console.log(this.company);
          }
        );
     }
}

And in the html file I have:

<section class="content-header">
    <h1>New Test <small>{{company.name}}</small></h1>
</section>

And then this gives an error "name of undefined" but when I replace it with:

<section class="content-header">
        <h1>New Test <small>{{company}}</small></h1>
    </section>

this will show [object Object]. And in the console, data is filled. So how to display it correctly in view?

1 Answer 1

3

Use the safe-navigation operator ?. to guard agains null or undefined while the data is not yet available

<h1>New Test <small>{{company?.name}}</small></h1>

You can also use *ngIf like

<h1 `*ngIf="company">New Test <small>{{company.name}}</small></h1>

to only render the element after the data becomes available.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.