Magnus Wallström
Magnus Wallström

Reputation: 1529

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

Upvotes: 6

Views: 20094

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202146

You need to instantiate the Person type:

constructor() {
  this.person = new  Person();
  this.person.id = 1;
  this.person.firstName = 'This';
  this.person.lastName = 'That';
}

In your case, the person property conforms to the Person type (at the structure level) but it's not actually an instance of the Person type since you define the object literally. This means that you need to define all the properties in your literal object and you won't be able to use the fullName getter since it's not part of this object. It's a kind of cast.

Use the following for convenience:

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

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

In this case, you can use the following:

export class AppComponent {
  title = 'Get property issue';
  person: Person = new Person(1, 'This', 'That');
}

Upvotes: 3

Ankit Singh
Ankit Singh

Reputation: 24945

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');
}

Upvotes: 9

Related Questions