-
directive is created in Angular7. The name is: NextTabDirective obtains this type of DOM element through QueryList query in a business component
@ViewChildren(NextTabDirective) inputs: QueryList<NextTabDirective>;
- then print out the result in the ngAfterViewInit of the component and print it out in the browser console to show that the data was not obtained
. What are the problems that will lead to the failure of the query using QueryList?
-
the problem that you have identified:
- the name of the self-made directive is NextTabDirective, which is certainly true. The name is copied .
-
this directive is introduced through import in the root module app.module.ts of the project:
import { NextTabDirective } from "./shared/ccDirective/next-tab.directive";
is also declared in the declarations of @ NgModule.
-
the header (top) is also introduced in the ts file of the business component:
import { NextTabDirective } from "src/app/shared/ccDirective/next- tab.directive";
- Project structure is:
app
|--> app.module.ts
|--> sharedccDirectivenext-tab.directive.ts
|-> pagesorderorder.component.html <-- Business component html template file
|-> pagesorderorder.component.ts <-- Business component ts file -
the following is the whole code for customizing directive
import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[next-tab]" }) export class NextTabDirective { self:any; nextControl:any; @HostListener("keydown.enter", ["$event"]) onEnter(event: KeyboardEvent) { if (this.nextControl) { if (this.nextControl.focus) { this.nextControl.focus(); this.nextControl.select(); event.preventDefault(); return false; } } } constructor(private control: ElementRef) { this.self=control.nativeElement; } }
The code for using custom directive in the tag of - order.component.html is as follows:
< input type= "text" next-tab >
:
,
@ViewChildren(NextTabDirective) inputs: QueryList<NextTabDirective>;
thanks for any help..