3

I want to return multiple values, such as 'firstname' and 'secondname' separately. How can I do this?

I tried to return them as a string, but it's not working:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pageheader : string = 'text';
  imagepath : string = 'https://3wga6448744j404mpt11pbx4-wpengine.netdna-ssl.com/wp-content/uploads/2018/11/Treehouse-Logo-Green-Large.png';
  firstname : string ='Tom';
  secondname : string =' Hopkins';
  getfullName(): string 
  {
      return this.firstname;
      return this.secondname
  }
1
  • 2
    You can't add multiple return statements in a single block, instead you can return object having both values and use it whereever you want! Commented Nov 29, 2018 at 11:09

3 Answers 3

1

You can't add multiple return statements in a single block, instead, you can return object having both values and use it wherever you want, for example -

getfullName() {
      return {firstName: this.firstname, lastName: this.secondname}
}
Sign up to request clarification or add additional context in comments.

Comments

1

Javascript function returns a single value, so in this case you can return an object, array, string value

Object

getfullName() {
      return {firstName: this.firstname, lastName: this.secondname}
}

Array

getfullName() {
      return [this.firstname,this.secondname];
}

String

getfullName() {
      return `${this.firstname} ${this.secondname}`;
}

Another way you can create a function that returns different name every time it called based on array

Component

  selectedName ='';
  names = ['Tom','Hopkins','Other'];
  index =-1;
  getNames() {
      this.index++;
      if (!this.names[this.index]){
        this.index  = 0
      }
    return this.names[this.index];
  }

  setSelectedName(){
    this.selectedName = this.getNames();
  }

Template

<button (click)="setSelectedName()">Get Name</button> {{selectedName}}

stackblitz demo

Comments

0

If you want full name with your getFullName() just use like...

getfullName() {
  return `${this.firstname} ${this.secondname}`
}

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.