Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I can't seem to find the 'correct' way to access a DOM element in an up-to-date way for:
Angular2 + Ionic2 + TypeScript.

So given this scenario below...

Q) How do i get access to sketchElement in the sign() function?

Settings.ts template:

<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">

My settings.ts class:

@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.      
  }
}
like image 819
Dave Avatar asked Mar 08 '16 14:03

Dave


People also ask

How do I access the DOM element of another component in angular?

Using nativeElement object we can access all DOM elements in Angular. @Viewchild/@Viewchildren — Select child or all children elements from the DOM. AfterViewInit — One of this Lifecycle hook is called after the Angular component initialized its view.

Can we access DOM element inside angular component constructor method?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }

What is DOM in TypeScript?

The Document Object Model (DOM) is a programming interface implemented by browsers in order to make static websites functional. The DOM API can be used to change the document structure, style, and content.


1 Answers

You can use the ViewChild decorator. First add :

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

and in your component, add the corresponding property:

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

  ngAfterViewInit() {
    // sketchElement is usable
  }
}

See this plunkr: http://plnkr.co/edit/0TV3ppA0Gpwr5CjOWlAu?p=preview.

This question could also help you:

  • Calling a function in a child Angular2 Component?
like image 59
Thierry Templier Avatar answered Oct 04 '22 04:10

Thierry Templier