Why is document null?

2019-06-13 19:19发布

**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)?

3条回答
乱世女痞
2楼-- · 2019-06-13 20:09

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):

import { Component, ViewChild, AfterViewInit, ElementRef   } from '@angular/core';

export class AppComponent {

    @ViewChild('firstControl') firstControl: ElementRef;

    skipLink() {
        console.log(this.firstControl);
        //if (this.firstControl) { this.firstControl.focus(); }
    };

.

<a href="#content-start" id="skipLink" (click)="skipLink()">Skip to main content</a>

Unfortunately, this is no better. this.firstControl is undefined.

查看更多
冷血范
3楼-- · 2019-06-13 20:16

This is happening because the DOM is not yet loaded in ngOnInit. Update your code to look like this, implementing AfterViewInit:

export class AppComponent implements AfterViewInit{
constructor(
    @Inject(DOCUMENT) private document: any
) { }
}

ngAfterViewInit() {

    this.document.getElementById('skipLink').onclick = skipLink;
    this.document.getElementById('skipLink').onkeypress = function (e) {
        if (e.keyCode == 13) {
            skipLink();
        }
    }

    function skipLink() {
        let content: HTMLElement = this.document.querySelector("#content-start"); // ?? document is null!!
        if (content) {
            let control: HTMLElement = this.document.querySelector('input, button, a');
            console.log(control);
            if (control) {
                // control.focus(); // first only
            }
        }
    }
}

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.

查看更多
Anthone
4楼-- · 2019-06-13 20:17

As you found out, skipLink should be a method of your component class. In order to maintain the correct this inside of skipLink, you can set the event handlers with addEventListener and arrow functions:

public ngOnInit() {
    this.document.getElementById('skipLink').addEventListener("click", () => { 
      this.skipLink(); 
    });
    this.document.getElementById('skipLink').addEventListener("keypress", (e) => {
        if (e.keyCode == 13) {
            this.skipLink();
        }
    }
}

private skipLink() {
    let control: HTMLElement = this.document.querySelector('input, button, a');
    if (control) {
        control.focus();
    }
}

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 with ViewChild, and get the HTML element itself with the nativeElement property. As for the event handlers, you can set them with Angular binding (e.g. (click)="skipLink()").

That method is shown in this plunker:

import { Component, NgModule, Inject, ElementRef, ViewChild } from '@angular/core';
...

@Component({
    selector: 'my-app',
    template: `
        <button #firstButton>Focusable Button</button>
        <br/>
        <button (click)="skipLink()">Click here to set focus on first button</button>
    `,
    ...
})
export class App {

    @ViewChild("firstButton") private firstButton: ElementRef;

    private skipLink() {
        this.firstButton.nativeElement.focus();
    }
}   
查看更多
登录 后发表回答