如何从页面将数据传递给离子自定义子组件

时间:2018-06-18 14:19:42

标签: angular ionic-framework

我正在尝试将变量从页面传递到我的自定义子组件,并记录为“未定义”。我想在子组件中使用此值,以便我可以调用另一个服务来加载子组件。 请帮忙。

child.component.ts

    import { Component, Input , OnInit} from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';


@Component({
  selector: 'well-subsurface',
  templateUrl: 'well-subsurface.html'
})
export class WellSubsurfaceComponent {

  @Input() data;
  wID: string;

  constructor(
    public navParams: NavParams) {


  }

  async ngOnInit() {

    this.wID = this.data;
    console.log("------ "+ this.wID)

  }

}

parent.component.ts

 import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';


@IonicPage()
@Component({
  selector: 'page-asset',
  templateUrl: 'asset.html',
})
export class AssetPage {
 public wID: any;


  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public alertCtrl: AlertController
  ) {
  }

  MenuContorl(assetID) {
  this.wID = wID;
  }
}

parent.html

<well-subsurface></well-subsurface>

1 个答案:

答案 0 :(得分:1)

假设您正确输入了<well-subsurface [data]="wID"></well-subsurface>这样的数据,那么就不应该使用ngOnInit,而是使用ngAfterContentInit

正如this angular lifecycle-hooks documentation所述,ngOnInit并不保证输入数据已通过@Input准备就绪,而ngAfterContentInit则可以。