Passing Parameter to Angular2 Component

how to pass data from one component to another in angular 6
how to pass data from one component to another in angular 7
angular pass html to component
angular pass component as parameter
angular pass data to child component
how to pass value from html to component in angular 6
angular input and output same property
input and @output in angular 6

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?

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

Passing Data into a Component, Passing Data into a Component. There are two ways to pass data into a component, with 'property binding' and 'event binding'. In Angular, data and event change detection happens top-down from parent to children. The point of making components is not only encapsulation, but also reusability. We can now use our component The @Input () decorator defines a set of parameters that can be passed down from the component's parent. For example, we can modify the HelloComponent component so that name can be provided by the parent. The point of making components is not only encapsulation, but also reusability.

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'"

Passing data into Angular components with @Input, to another (typically parent to child). This custom input binding is created via the @Input() decorator! Passing data into Angular components with @Input. In a component-driven application architecture we typically use stateful and stateless components. The key concept is having some form of “stateful” component that delegates data and perhaps tasks (in the form of events) into a “stateless” child, or children, component.

You need to create a number variable in your component too that will hold the value.

import {Component, OnInit} from '@angular/core';
@Component({
  selector: 'myComponent',
  template: 
    `<h1>Returned Value {{returnedString}}</h1>,`, 
  inputs:['myNum']
})
export class MyComponent implements OnInit { 
  myStringArray: string[] = ['First','Second','Third','Forth','Fifth','Sixth']; 
  returnedString: string;
  public myNum: number;  <= here is your variable

  ngOnInit() {
      //you can use this.myNum anywhere now like this
      this.returnedString = 'number '+ this.myStringArray[this.myNum];
  }

  constructor(){

  }
}

You may have to change the name of your input because number is a keyword.

Another Note: You have to use OnInit instead of constructor to start using your inputs. ngOnInit is an Angular2 lifecycle method that is called by Angular when it's done building the component and evaluated the bindings

Component interaction, Pass data from parent to child with input bindinglink Use an input property setter to intercept and act upon a value from the parent. The setter of the name input  I would consider changing slightly the design. Instead of inserting content between <list> and </list> and reference such content via ng-content in the List component, I would create a Component that plays the role of content (i.e. "repeat template with local variables passed, so each item is different") with the required input variables and insert the Component into the list.

Here is another alternative. It demonstrates how to use a getter for returnedString. Less code needed than with ngOnChanges.

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

@Component({
  selector: 'my-cmp',
  template: `
    <p>returnedString = {{ returnedString }}</p>
  `
})
export class MyComponent {
  myStringArray: string[]  = ['First','Second','Third','Forth','Fifth','Sixth'];
  @Input() stringIndex: number;

  get returnedString(): string {
    if (this.stringIndex !== undefined) {
      return this.myStringArray[this.stringIndex];
    }
  }
}

Pass Values into Angular 2 Components with @Input from , Input allows you to pass data into your controller and templates through html and defining custom properties. This allows you to easily reuse components and  Passing data from a Nested Component. In the previous example I showed how the container can pass data to the nested component by binding to a nested component's property, that is declared with the @Input decorator. If the nested component wants to send information back to its container, it can raise an event.

It's quite simple. See this demo. Let's say you have two components parent and child. And you want to pass a variable to child and modify it there, say views.

On parent template:

<child [(views)]="views"></child>

On child component:

  @Input() views: number;
  @Output() viewsChange = new EventEmitter<number>();

  // Bind this function to button click or some events:
  updateViews() {
    this.views++;
    this.viewsChange.emit(this.views); // Emit the value to parent:
  }

Detail explanation: When you bind [(views)] in parent, it is acting as:

<child 
        [views]="views" 
        (viewsChange)="views = $event">
</child>

So, it is listening to viewsChange output function. Whenever, you do viewsChange.emit, the parent views get updated.

Gotcha: The output function should be precisely named $var + "Change". If you chose to name something else you will have to do:

<child 
            [views]="views" 
            (customEmitterFunction)="views = $event">
    </child> 

Passing data to and from a nested component in Angular 2, Luckily, in Angular 2 the communication between components is a lot In our example, we'll pass a string value to the nested component's title  EDIT : SOLUTION After upgrading to 2.0 Final - Passing server parameters to ngModule after RC5 upgrade ===== Any way to have server parameters passed to an Angular 2 application? i.e. I would like to use the MVC object "HttpContext.User.Identity.Name" and have it injectable anywhere in my angular 2 app.

Angular Components: Pass by Reference or Pass by Value?, As you see, we are passing data (object) and count (number) to the child component. Since data is being passed as an object, it will "Pass by  to pass many options you can pass a object to a @Input decorator with custom data in a single line. In the template

Angular 2 Components: Inputs and Outputs, David Aden discusses Angular 2 components, looking at how they're is available in CompDemo by passing “ $event ” as an argument to the  There are many scenarios, where you need to pass parameters to the route. For example, to navigate to the product detail View, we need to pass the product ID, so that component can retrieve it and display it to the user.

Passing data between nested components with Angular, One of the biggest changes from AngularJS to Angular (2+) is the step away from. binding in Angular, data is passed down through components and if when you declare a variable and assign it a value where the variable  There is no parent child relationship between components A and B, so we cannot use first two methods to pass the data. We could use route parameters and pass some identifier to the routed

Comments
  • Thats it. So i needed the @Input() xxxx:number and the import at the top editied and then the ngOnChanges()....
  • Yes. In a more advanced case you might want to also implement ngOnDestroy incase you are creating large objects that need to be destroyed when the component is destroyed.
  • Apologies...that didnt work, sorry for jumping the gun there. Im still getting undefined
  • what are you using this line for inputs:['number']?
  • Guys, the OnChanges interface is ONLY for your IDE and the compiler. Angular doesn't care if it's here or not. It's a way of saying to the IDE and TS compiler "this class must have an ngOnChanges method to be valid". You DO NOT have to write implements OnChanges or import the OnChanges for the code to work... If the ngOnChanges() exists, then Angular will call it. Full stop.
  • Actually attributes between [...] are interpreted as JavaScript code, thus the need to use quotes. To pass simple strings one can use attributes directly. Your sample would be: <myComponent stringvar="string value"></myComponent>
  • That was one of the issues. Other could be, you have to use ngOnInit, the value of input isn't yet available in the constructor. Give a try to updated answer now
  • still undefined. I had to put both the import {OnInit} from '@angular/core'; and the import { Component } from '@angular/core'; in as it failed with just the onInit
  • is it how i pass it from the calling class?
  • Try sending it like <myComponent [myNum ]="1"></myComponent>
  • Try to` console.log` this.myNum in your ngOnInt event, does it contains a nnumber?