【问题标题】:Passing params to a component in Ionic 2将参数传递给 Ionic 2 中的组件
【发布时间】:2018-08-29 22:19:34
【问题描述】:

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

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

如果我直接从视图中访问节点,它可以工作&lt;div *ngFor="let selected of node"&gt;

但是我怎样才能访问从组件代码本身传递给组件的参数呢?

【问题讨论】:

    标签: angular typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    来自Angular2 docs,您可以

    使用输入属性设置器截取来自的值并对其进行操作 父母。

    子组件:

    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...
      }
    }
    

    【讨论】:

    • 再次非常感谢您帮助我,我的下一个问题被困住了,如果您不介意看看,当您有空的时候? stackoverflow.com/questions/38986839/…,再次感谢您的帮助
    • 很高兴能帮上忙 :) 当然,我会看看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2017-11-29
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2016-04-07
    • 2021-01-18
    相关资源
    最近更新 更多