**更新**,使用接近工作的解决方案:
我试图让“跳到内容”链接跳转到“#content-start”之后的第一个可聚焦元素。
登录库.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();
}
}
}
}
登录.组件.html:
<div class="login-page">
<section class="main container" id="content-start">
<input type="text"/>
这实际上是有效的,因为控制台.log(控制) returns
<input _ngcontent-c4="" id="username" name="username">
这实际上是正确的控制。
但我不能只设置 .focus() 因为我拥有的是 HTML 片段,而不是具有方法的对象,例如 .focus();
呃,是否有 jQuery 的 $(control) 的角度等效项?
发生这种情况是因为 DOM 尚未加载ngOnInit
。更新您的代码,使其看起来像这样,实施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
确实如其听起来那样;它仅在视图最初加载后运行。
编辑以回应您的问题的编辑: 您正在寻找角元 https://docs.angularjs.org/api/ng/function/angular.element。有关这方面的文档非常有帮助,并且是在 Angular 中操作元素的更好的编程实践。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)