我试图将参数(哈希对象)从我的页面之一传递给组件。
我可以从组件的视图访问对象。但是我想要的是先从代码(.ts
)中读取它,然后传递给视图。
这是我的代码
#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>
如果我直接从视图访问该节点,那么它将起作用 <div *ngFor="let selected of node">
但是,如何从组件代码本身访问传递给组件的参数呢?
从Angular2文档中,您可以
使用输入属性设置器来拦截父级的值并对其进行操作。
子组件:
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; }
}
父组件:
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 '];
}
因此,您的代码如下所示:
@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...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句