sameera207 sameera207 - 3 months ago 41
TypeScript Question

passing params to a component - Ionic 2

I'm trying to pass a parameter (a hash object) from one of my pages to a component.

I can access the object from the view of the component. But what I want is to read it first from the code (

.ts
) and then pass to the view.

This is my code

#main page component
<selected-options [node]="node"></selected-options>

#selected-options component code
import { Component, Input } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
selector: 'selected-options',
templateUrl: 'build/components/selected-options/selected-options.html',
inputs: ['node']
})
export class SelectedOptions {

@Input() node: any;
private selectedNodes: any;

constructor(public ryvuss: Ryvuss, public nav: NavController, public navParams: NavParams) {
// I want to read the node object in here
this.node = navParams.get('node');
this.selectedNodes = //dosomething with node
}
}

#selected-options component html view
<div *ngFor="let selected of selectedNodes">
//loop
</div>


If I directly access the node from view it works
<div *ngFor="let selected of node">


But how can I access the params passed in to the components from component code itself ?

thanks in advance

cheers

Sam

Answer

From Angular2 docs, you can

Use an input property setter to intercept and act upon a value from the parent.

Child component:

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

@Component({
  selector: 'name-child',
  template: `
    <h3>"{{name}}"</h3>
  `
})
export class NameChildComponent {

  _name: string = '<no name set>';

  @Input()
  set name(name: string) {
    // Here you can do what you want with the variable
    this._name = (name && name.trim()) || '<no name set>';
  }

  get name() { return this._name; }
}

Parent component:

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

@Component({
  selector: 'name-parent',
  template: `
    <h2>Master controls {{names.length}} names</h2>
    <name-child *ngFor="let name of names"
      [name]="name">
    </name-child>
  `
})
export class NameParentComponent {
  // Displays 'Mr. IQ', '<no name set>', 'Bombasto'
  names = ['Mr. IQ', '   ', '  Bombasto  '];
}

So your code would look like:

@Component({
  selector: 'selected-options',
  templateUrl: 'build/components/selected-options/selected-options.html'
})
export class SelectedOptions {

  private selectedNodes: any;      

  @Input()
  set node(node: any) {
    // Here you can do what you want with the variable
    this.selectedNodes. = ...;
  }

  constructor(public ryvuss: Ryvuss, public nav: NavController) {
    // your code...
  }
}
Comments