Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get properties in Angular 2 using Typescript

I'm trying to make the property fullName display the first and the last name. How to make the get property to work?

See this Plunk.

import { Component } from '@angular/core';

export class Person {
  id: number;
  firstName: string;
  lastName: string;
  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Component({
  selector: 'my-app',
  template:`
    <h1>{{title}}</h1>
    <p>My first name is {{person.firstName}}</p>
    <p>My last name is {{person.lastName}}</p>
    <h2>My full name is {{person.fullName}}!</h2>`
})
export class AppComponent {
  title = 'Get property issue';
  person: Person = {
    id: 1,
    firstName: 'This',
    lastName: 'That'
  };
}

EDIT What I actually wanted to achieve was how to use get properties when calling a service and subscribing for the result. But I managed to figure it out based on below answers. Thanks!

See my updated plunk

like image 991
Magnus Wallström Avatar asked May 18 '16 12:05

Magnus Wallström


1 Answers

Working PLUNKER

Try this

import { Component } from '@angular/core';

export class Person {
  constructor(public id: number,public firstName: string, public lastName: string){}

  get fullName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

@Component({
  selector: 'my-app',
  template:`
    <h1>{{title}}</h1>
    <p>My first name is {{person.firstName}}</p>
    <p>My last name is {{person.lastName}}</p>
    <h2>My full name is {{person.fullName}}!</h2>
    `
})
export class AppComponent {
  title = 'Get property issue';
  person: Person = new Person( 1, 'This', 'That');
}
like image 171
Ankit Singh Avatar answered Sep 28 '22 07:09

Ankit Singh