页面代码中的 ionic 2 引用来自动态数组的组件

ionic 2 reference in the page's code a component from dynamic array

我有一个 幻灯片 填充了 *ngFor 包含相同自定义组件的实例数组(canvas 像 img 一样使用),我需要,在页面的 .ts 中使用这个 slides,来访问当前选择的组件并调用它的一些方法,比如:

let curr: MyComponent = this.slides[selected];

注意数组可能会改变,所以在 constructors/init 上不能是静态的。

我知道如何在一个元素上使用 #referenceElementRef@ViewChild,但我不知道访问数组中的一个元素的语法。

编辑

我用 plunker 做了一个例子,但我没有注册,也不知道 the link 会持续多久,所以下面是来自 angular2+typescript plunker 项目的修改源(抱歉,我只知道现在这是一个只有 angular2 的问题,不是 ionic)

所以,我需要的是,从 App.current() 实现访问元素实例 i 作为 MyCoolComponent

let curr: MyCoolComponent = ?

src/app.ts:

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {MyCoolComponent} from './MyCoolComponent'
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div *ngFor="let item of texts; let i = index">
        <my-cool text="{{item.text}}" (click)="current(i)"></my-cool>
      </div>
    </div>
  `,
})
export class App {
  name:string;
  texts = [ 
    { text: "test1" },
    { text: "test2" },
    { text: "test3" }
  ]
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  current(i) {
    console.log('current: ',i)
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, MyCoolComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

src/MyCoolComponent.ts:

import {Component, Input} from '@angular/core'

@Component({
  selector: 'my-cool',
  template: `
    cool {{text}}
  `,
})
export class MyCoolComponent {
  @Input('text') text:String;
  constructor() {
    this.text = `test`
  }
}

组件一般不会被注入到pages/other组件中。这就是服务的目的。因此,您将无法 "call" 组件的功能。

您的组件不是事件处理程序。如果你有一个需要处理的事件,应该由组件自身封装,如果需要,发送给它的父级 component/page.

否则..我将创建一个包含组件及其 ElementRef 的对象。每次数组更改时更新这些值即可。