**UPDATED ** with a solution that comes close to working:
I'm trying to get my 'skip to content' link to jump to the first focusable element after '#content-start'.
login-base.component.ts:
import { Component, OnInit } from '@angular/core';
import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class BaseLoginComponent implements OnInit {
constructor(
@Inject(DOCUMENT) private document: any
) {
}
skip() {
console.log(document);
console.log(document.querySelector);
var content = document.querySelector(`#content-start`); // ?? document is null!!
if (content) {
var control = content.querySelector('input, button, a');
console.log(control);
//if (control) {
// control.focus(); // first only
//}
}
};
ngOnInit() {
this.document.getElementById('skipLink').onclick = this.skip;
this.document.getElementById('skipLink').onkeypress = function (e) {
if (e.keyCode == 13) {
this.skip();
}
}
}
}
login.component.html:
<div class="login-page">
<section class="main container" id="content-start">
<input type="text"/>
This actually works, inasmuch as console.log(control) returns
<input _ngcontent-c4="" id="username" name="username">
which is actually the correct control.
But I can't just set .focus() because what I have there is an HTML snippet, not an object with methods, such as .focus();
Uh, is there an angular equivalent of jQuery's $(control)?
This has drifted pretty far from the original implementation; if I update the opening post, the comments will make no sense.
Following Kevin's advice to implement as per Using ViewChild in Angular to Access a Child Component, Directive or DOM Element, (unless i'm misunderstanding):
.
Unfortunately, this is no better. this.firstControl is undefined.
This is happening because the DOM is not yet loaded in
ngOnInit
. Update your code to look like this, implementingAfterViewInit
:ngAfterViewInit
does exactly what it sounds like; it only runs once the view is initially loaded.Edit in response to your question's edit: You're looking for angular.element. The documentation on this is really helpful, and is better programming practice for manipulating an element in Angular.
As you found out,
skipLink
should be a method of your component class. In order to maintain the correctthis
inside ofskipLink
, you can set the event handlers withaddEventListener
and arrow functions:You can see the code at work in this plunker.
As mentioned by Kevin, using
ViewChild
is a more standard way to refer to an element in a component. You can define a template reference variable on the target element (e.g.#firstButton
in the component template below), get a reference to it withViewChild
, and get the HTML element itself with thenativeElement
property. As for the event handlers, you can set them with Angular binding (e.g.(click)="skipLink()"
).That method is shown in this plunker: