Ionic2/Angular2/TypeScript:如何访问函数中的 DOM 元素 2016

Ionic2/Angular2/TypeScript: How to access a DOM element in a function 2016

我似乎找不到 'correct' 以最新方式访问 DOM 元素的方法:
Angular2 + Ionic2 + TypeScript.

所以在下面这个场景中...

Q) 如何在 sign() 函数中访问 sketchElement

Settings.ts 模板:

<button full class="top-button-margin" (click)="sign()">
  Sign
  <ion-icon name="create"></ion-icon>
</button>
<img id="sketchElement" src="img/logo.png" padding *ngIf="showSignatureView">

我的settings.tsclass:

@Page({
  templateUrl: 'build/pages/settings/settings.html'
})
export class SettingsPage {

  private currentUser: User = <User>{};
  private loggingOut: boolean = false;
  private currentConnection: string = "";
  private showSignatureView: boolean = false;

  constructor(
    private _platform: Platform,
    private _nav: NavController,
    private _events: Events,
    private _LoginService: LoginService,
    private _SessionService: SessionService,
    private _UIService: UIService) {

  }

  sign() {
    // I want to access sketchElement and its properties here.      
  }
}

您可以使用 ViewChild 装饰器。首先添加:

<img id="sketchElement"
     #sketchElement
     src="img/logo.png" padding *ngIf="showSignatureView">

并在您的组件中,添加相应的 属性:

@Page({
  templateUrl: 'build/pages/settings/settings.html'
})
export class SettingsPage {
  @ViewChild('sketchElement')
  sketchElement:ElementRef;

  ngAfterViewInit() {
    // sketchElement is usable
  }
}

看到这个 plunkr:http://plnkr.co/edit/0TV3ppA0Gpwr5CjOWlAu?p=preview

这个问题也可以帮到你:

  • Calling a function in a child Angular2 Component?

我对 Ionic 和 Angular 我自己都很陌生,但我也看到有人通过使用 ElementRef 的代码通过指令做一些事情。
我看到这是在 d3 项目的上下文中使用的 他们在哪里:

import * as d3 from 'd3';

然后他们添加了一个图像 svg。
在指令构造函数中使用了这种代码:

import {ElementRef} from '@angular/core';
constructor (private elementRef : ElementRef) {
   let el = this.elementRef.nativeElement;
   var svg = d3.select(el).append('svg');
} 

也许这可以添加到您的构造函数中。