angularangular2-templateangular2-formsangular2-servicesangularjs-templates

How to print object properties in template in Angular2


I am new to angular2, And trying to bind object result to the html template. I am able to get data from srtvice by using Observable. I am able to see JSON data in console and in template as well. But when I try to access property from result json, It's not showing data as below image.

Output

Below is my code of that componenet,

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { JuniorService } from '../Service/service.junior';
import { Employee } from '../../models/Employee';


@Component({
  selector: 'my-getjunior',
  template: `<h1>Details of {{id}} 
  <hr/>
  JSON :  {{Junior | json}} 
  <hr/>
  Summary :  {{junior?.summary}}</h1>`
  //templateUrl: './app/Junior/get/junior.get.html'
})
export class JuniorGet implements OnInit
 {

errorMessage: string;
Junior: Employee;
id: number;
private sub: any;

  constructor (private juniorService: JuniorService, private route: ActivatedRoute) {

 }

  ngOnInit(){
      this.sub = this.route.params.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number
     this.getJunior(this.id);
    });
  }

    getJunior(id) {
      this.juniorService.getById(id)
                      .subscribe(
                        data => {
                            this.Junior = data;
                            console.log("Junior data", this.Junior);
                          },
                        error =>  this.errorMessage = <any>error);
  }


}

I am calling service on imit method and that data I want to see in template.

Where else do I need to change to print data?


Solution

  • use your code like this

    {{Junior?.summary}}
    

    there is small typo in your code you are using junior instead of Junior

    and not thorwing any error in console because you have used safe navigation (?) in your code