Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameter to Angular2 Component

Tags:

html

angular

I'm Learning Angular2 so be gentle... I have a basic Component which has a string array. I want to pass an integer to this component and have it return the string found at the index of that parameter.

E.g. myComponent[number]=1 returns string "second element".

My code so far is this:

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

@Component({
  selector: 'myComponent',
  template: 
    `<h1>Returned Value {{returnedString}}</h1>,`, 
  inputs:['number']
})
export class MyComponent  { 
  myStringArray: string[]; 
  returnedString: string;

  constructor(){
    this.myStringArray = ['First','Second','Third','Forth','Fifth','Sixth'];
    this.returnedString = 'number'+this.myStringArray['number'.valueOf()];
  }
}

I am calling this component as follows

<myComponent [number]=1></myComponent>

I print the value returned to the screen and get 'undefined'.

Any ideas folks?

like image 926
Fearghal Avatar asked Jan 29 '17 22:01

Fearghal


2 Answers

Since you want to bind to a custom property import Input and OnChanges from core and then implement as Input to create your custom property. The OnChanges just ensures your value gets updated when the bound value changes.

Remove the inputs key from your component decorator

import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'myComponent',
  template: 
    `<h1>Returned Value {{returnedString}}</h1>,`
})
export class MyComponent  implements OnChanges { 
  myStringArray: string[];
  returnedString: string;
  @Input() inputNumber: number; 

  constructor(){
    this.myStringArray = ['First','Second','Third','Forth','Fifth','Sixth'];
    this.returnedString = 'number'+this.myStringArray[Number(this.inputNumber)];
  }

  ngOnChanges() {
    this.returnedString = 'number'+this.myStringArray[Number(this.inputNumber)];   
  }
}

Update your code usage to the following

<myComponent [inputNumber]="1"></myComponent>

Here is a sample plunker. https://plnkr.co/edit/S074zoVJ3ktQDKkcQgxe?p=preview

like image 169
Evans M. Avatar answered Sep 22 '22 14:09

Evans M.


I had tough time to send string inputs. here is the correct way,

<myComponent [stringvar]="'string value'"></myComponent>

"string value" will not work. angular expecting object or number inside double quotes. string should be inside single quotes within double quotes "'string'"

like image 36
Som Avatar answered Sep 19 '22 14:09

Som