我是角度2的新手 . 如何将焦点移动到Angular 2中的键输入的下一个控件 . 我implement this code但是如何不正常工作 . 请建议我如何做到这一点 . 谢谢
我的组件代码
import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter, Output, Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
import {Http, Response} from '@angular/http';
import {TestService} from '../../services/test.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { RouterModule } from '@angular/router';
import { ActivatedRoute,Params } from '@angular/router';
@Component({
selector : 'test_block',
templateUrl : './partials/test_block.html',
providers: [TestService]
})
@Directive({
selector: '[test_block]'
})
export class TestComponent {
private el: ElementRef;
@Input() test_block: any;
branch_outstanding:any = [];
charges:any = [];
searched_charges:any = [];
constructor(private test_service:TestService, @Inject(ActivatedRoute) private route: ActivatedRoute, private _el: ElementRef,public renderer: Renderer) {
this.el = this._el;
}
@HostListener('keydown', ['$event']) onKeyDown(e:any) {
if ((e.which == 13 || e.keyCode == 13)) {
e.preventDefault();
let control:any;
control = e.srcElement.nextElementSibling;
while (true){
if (control) {
if ((!control.hidden) &&
(control.nodeName == 'INPUT' ||
control.nodeName == 'SELECT' ||
control.nodeName == 'BUTTON' ||
control.nodeName == 'TEXTAREA'))
{
control.focus();
return;
}else{
control = control.nextElementSibling;
}
}
else {
console.log('close keyboard');
return;
}
}
}
}
}
在控制台中显示错误:
未处理的Promise拒绝:无法编译'TestComponent',因为它不是一个组件 . ;区域:;任务:Promise.then;值:错误:无法编译'TestComponent',因为它不是组件 .
我不知道这段代码有什么问题 . 请建议我 .
3 回答
终于得到了解决方案
我为TestComponent创建了两个不同的装饰器,提到@Component和@Directive .
之后@Directive我像这样导入我的
test.module.ts
import { TestDirective } from './test.directive';
这在html bind
<input test_block type="text">
中非常重要,如果你没有绑定test_block
那么代码工作不正常可能缺少声明,将TestComponent添加到app.module.ts的声明中
用途非常有限 . 例如,使用bootstrap css时它不起作用 . 因为使用renderer2,无法访问子节点