2

我正在尝试将参数(哈希对象)从我的一个页面传递给组件。

我可以从组件的视图访问对象。但我想要的是先从代码(.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">

但是如何访问从组件代码本身传递给组件的参数呢?

4

1 回答 1

4

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...
  }
}
于 2016-08-16T09:14:17.973 回答