Ionic 2 - 如何从指令内部访问组件



我正在尝试构建一个指令来显示自定义小键盘,当单击应用指令的控件(输入)。我正在研究Ionic 2 RC5。

我的页面.html

<ion-content>
  <ion-item>
      <ion-label stacked>Label</ion-label>
      <ion-input dirNumpad type="text" [(ngModel)]="myField"></ion-input>
  </ion-item>
</ion-content>
<ion-footer>
  <numpad #idNumpad hidden></numpad>
</ion-footer>

数字键盘组件位于页面底部的 DOM 中。

目录数字垫

import { Directive, ElementRef, ViewChild } from '@angular/core';
import { Numpad } from '../../components/numpad/numpad';
@Directive({
  selector: '[dirNumpad]',            // Attribute selector
  host: {
      '(click)':          'onClick()'
  }
})
export class DirNumpad {
  @ViewChild('idNumpad') numpad: Numpad;
  constructor( private el:    ElementRef ) {
  }
  onClick() {
      this.showNumpad();
  }
  showNumpad() {
      console.log(this.numpad);   => undefined
      this.numpad.show();     => error: show property does not exist on undefined
  }
}

小键盘.html

<div class="numpad" style="position:absolute; top:auto; left:0; right:0; bottom:0; height:150px;">My Numpad</div>

数字键盘

import { Component, Input } from '@angular/core';
@Component({
  selector: 'numpad',
  templateUrl: 'numpad.html'
})
export class Numpad {
  constructor() {}
}

的问题:我无法通过 ViewChild 从指令内部访问数字键盘组件。console.log(this.numpad)总是返回"undefined"!只有当用户单击应用指令的输入时,我才需要它显示数字键盘......

我做错了什么?我遇到了这个问题,所以任何帮助将不胜感激。

ViewChild 仅适用于该项目的子项。由于该组件在任何指令中都不是子组件,而是同级组件,因此无法在 ViewChild 中接收该组件。

您可以将其作为输入的一部分传递

在组件中声明输入

import { Directive, ElementRef, Input } from '@angular/core';
import { Numpad } from '../../components/numpad/numpad';
@Directive({
  selector: '[dirNumpad]',            // Attribute selector
  host: {
      '(click)':          'onClick()'
  }
})
export class DirNumpad {
  @Input('numpad') numpad: Numpad;
  constructor( private el:    ElementRef ) {
  }
  onClick() {
      this.showNumpad();
  }
  showNumpad() {
      console.log(this.numpad);   => undefined
      this.numpad.show();     => error: show property does not exist on undefined
  }
}

并将其设置在您的 HTML 中

<ion-content>
  <ion-item>
      <ion-label stacked>Label</ion-label>
      <ion-input dirNumpad [numpad]="idNumpad" type="text" [(ngModel)]="myField"></ion-input>
  </ion-item>
</ion-content>
<ion-footer>
  <numpad #idNumpad hidden></numpad>
</ion-footer>

最新更新