Passing params to a component in Ionic 2
12,033
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...
}
}
Related videos on Youtube
Author by
sameera207
Rails developer, But will code anything for FOOD :D
Updated on September 15, 2022Comments
-
sameera207 over 1 year
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 ?
-
sameera207 over 7 yearsthanks a lot again for helping me out, I'm stuck with my next problem, if you dont mind having a look, when u get a free time 😬 stackoverflow.com/questions/38986839/…, thanks again for the help
-
sebaferreras over 7 yearsGlad I could help :) Sure, I'll take a look at it