6

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

2 Answers 2

9

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');
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

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.