Andrew Junior Howard Andrew Junior Howard -4 years ago 170
Javascript Question

Angular 2 - Get passed object to component via inputs

On my parent page I have a link here:

<a (click)="showPermissionsRates(5757);">Link</a>


The function sets it:

showPermissionsRates(item) {
this.currentEventPoolId = item;
}


With a child component on the parent page here:

<app-event-pools-permissions-rates [eventPoolId]="currentEventPoolId "></app-event-pools-permissions-rates>


And then in my child component TS file I use:

inputs: ['eventPoolId']


But how do I get that value of '5757' in the child component? Such as using alert?

Answer Source

You should be able to just use @Input() on the child property.

I've put this together showing a VERY basic example, but without more to go on regarding your issues, it's hard to know what you need: https://plnkr.co/edit/y9clOla1WrPFmhMJoz7o?p=preview

The gist is to use @Input() to mark your inputs in the child component, and map those in the template of the parent.

import {Component} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

import { ChildComponent } from 'child.component.ts';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="changeProperty('ABC 123')">Click Me!</button>
    
      <child-component [childProperty]="parentProperty"></child-component>
    </div>
  `,
})
export class App {
  public parentProperty: string = "parentProp";
  
  public changeProperty(newProperty: string) : void {
    this.parentProperty = newProperty;
  }
}

Then, in the child:

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

@Component({
  selector: 'child-component',
  template: `
    <div>Hello World: {{ childProperty }}</div>
  `,
})
export class ChildComponent {
  
  @Input()
  childProperty:string;
  
  constructor() {
    this.childProperty = 'childProp'
  }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download