1

我是新角度2.如何將焦點移到下一個控件上,然後輸入Angular 2中的按鍵。我不知道如何正常工作。implement this code請建議我如何做到這一點。由於使用Angular 2將焦點放在下一個輸入字段上並用Enter鍵按

我的組件代碼

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; 
       }    
      } 
     } 
    } 
} 

顯示錯誤控制檯:

Unhandled Promise rejection: Could not compile 'TestComponent' because it is not a component. ; Zone: ; Task: Promise.then ; Value: Error: Could not compile 'TestComponent' because it is not a component.

我不知道是什麼問題,這個代碼。請建議我。

+1

顯示你的代碼,那麼只有我們可以幫助 –

+1

我想這是因爲你使用兩個裝飾單個類。 – Pengyy

+1

我在哪裏更改代碼,你可以向我簡要介紹@Pengyy –

回答

2

添加TestComponent報關單最後得到了解決

  1. 我創建了兩個不同的裝飾器TestComponent提@Component和@Directive。
  2. 是@Directive我導入到我的test.module.ts這樣
    import { TestDirective } from './test.directive';
  3. 這是在HTML綁定<input test_block type="text">很重要之後,如果你不綁定test_block然後代碼工作不正常
1

這可能是缺乏聲明,在app.module.ts

0

的使用是非常有限的。例如,它使用引導CSS時不起作用。 因爲renderer2,這是不可能訪問的childNodes

<div class="container-fluid"> 
<div class="row"> 
<div class="col-md-3"> 
<input type="number" class="form-control" required [onReturn]> 
</div> 
<div class="col-md-4"> 
<input type="number" class="form-control" required > 
</div> 
<div class="col-md-5"> 
<input type="number" class="form-control" required > 
</div> 
<div class="col-md-3"> 
<input type="number" class="form-control" required > 
</div> 
</div> 
</div> 
</div>