• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » How to Create Autofocus Directive Certain Elements Angular 4

How to Create Autofocus Directive Certain Elements Angular 4

By Sigit Prasetya Nugroho ∙ September 28, 2017 ∙ Javascript ∙ 2 Comments

Share : TwitterFacebookTelegramWhatsapp

Example autofocus directive angular 4. In Angular, using autofocus attribute unlike html5/javascript code in general. You need to create a directive first so that the code work well. This short tutorial I will share how to build and use autofocus directive in angular 4. Let’s see.

Read another article: Simple Login Form Angular 4 Tutorial For Beginner

Table of Contents

  • 1 What is auto focus attribute?
  • 2 Autofocus Directive in Certain Elements Angular 4
    • 2.1 So my article on focus on element directive in angular 4, may be useful

What is auto focus attribute?

Autofocus Directive Angular 4 Tutorial Free Min

According to w3schools.com, the autofocus attribute html5 is a boolean attribute. How it works is when the page loaded, then automatically focus on element. The use of the html5 autofocus attribute is as follows.

1
<input type="text" name="names" autofocus>

The problem is when you move the one to another pages using the angular router on single page application. Autofocus html5 only runs when the first time page loads. Unlike the SPA, all scripts loaded the first time. When we move pages, autofocus angular 4 on certain input elements will not work properly

Using native javascript, you can focus on the input field with the following commands

Related Articles :

  • Trick To Redirect New Window Or Tab With Post Method On Angular 5
  • Tutorial To Change Date Format Ng-bootstrap Datepicker Angular 5
  • Tutorial Simple CRUD Angular 5 And Lumen 5.6 For Beginners

1
document.getElementById("myTextField").focus();

Angular 4 cannot apply the above function directly although angular is javascript framework.

You need a directive so that the focus function to work properly in angular.

Autofocus Directive in Certain Elements Angular 4

Create a new angular project using Angular cli

1
ng new testfocus

create a new directive with the name “autofocus” using the following command

Create Autofocus Directive In Certain Element Angular 4

1
ng g directive autofocus

Then edit autofocus.directive.ts and copy the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Directive,Input, ElementRef, Renderer } from '@angular/core';
 
@Directive({
  selector: '[appAutofocus]'
})
export class AutofocusDirective {
  @Input() appAutofocus: boolean;
  private el: any;
  constructor(
    private elementRef:ElementRef,
  ) {
    this.el = this.elementRef.nativeElement;
  
  }
  ngOnInit(){
    this.el.focus();
  }
 
}

Create two components to test the directive script. We need two components to move from one page to another so that directive performance can be seen.

Create a home component using the following script

Create Home Component Angular 4

1
ng g component home

Create a test component using the following script

Create Test Component Angular 4

1
ng g component test

Edit test.component.html and copy the following script

1
2
3
4
5
6
7
8
9
10
11
12
<div>
  <label for="input1" input1>Input 1</label>
  <input type="text" #input1>
</div>
<div>
  <label for="input2" >Input 2</label>
  <input type="text"  #input2>
</div>
<div>
  <label for="input3">Input 3</label>
  <input type="text" appAutofocus #input3>
</div>

A brief description:

In this example, i putt appAutoFocus directive in the input boxes number 3

Create an angular routing with app.routing.ts name and copy the following code

1
2
3
4
5
6
7
8
9
10
11
12
import {NgModule }             from '@angular/core';
import {RouterModule, Routes } from '@angular/router';
import {HomeComponent} from './home/home.component';
import {TestComponent} from './test/test.component';
 
const appRoutes: Routes = [
     { path: 'home', component: HomeComponent },
     { path: 'test', component: TestComponent},
     { path: '**', redirectTo: '/home' }
];
export const routing = RouterModule.forRoot(appRoutes);

Open app.component.html and copy the following code

1
2
3
4
5
6
7
8
<!--The content below is only a placeholder and can be replaced.-->
<nav>
    <ul class="menu">
      <li class="is-active"><a routerLink="/home" routerLinkActive="active">home</a></li>
      <li><a routerLink="/test" routerLinkActive="active">test</a></li>
    </ul>
</nav>
<router-outlet></router-outlet>

Run the app with the following command

1
ng serve

Test the above script, and make sure your apps run well like the following gif image

Autofocus Directive Angular 4 Example

Little explanation:

Our focus on test.component.ts

  • To use autofocus directive angular 4 as good as using autofocus html5. Add the appAutofocus attribute to the input boxes we’ll focus on.
  • Make sure you have import directive on app.module.ts and run the apps.

But it would be different if we want to use the focus() function on the angular 4. In native javascript, we use the following code to autofocus on text input:

1
document.getElementById("myTextField").focus();

Angular requires @Viewchild decorator to interact with elements in component templates.

For example, add the following HTML code to test.component.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div>
  <label for="input1" input1>Input 1</label>
  <input type="text" #input1>
</div>
<div>
  <label for="input2" >Input 2</label>
  <input type="text"  #input2>
</div>
<div>
  <label for="input3">Input 3</label>
  <input type="text" appAutofocus #input3>
</div>
 
<button  (click)="focusin(1)">focusing input 1</button>
<button  (click)="focusin(2)" >focusing input 2</button>

Add some code to the following test.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Component, OnInit,ElementRef,ViewChild  } from '@angular/core';
 
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  @ViewChild('input1') focus1:ElementRef;
  @ViewChild('input2') focus2:ElementRef;
  constructor() { }
 
  ngOnInit() {
  }
  focusin(numb)
  {
    if(numb == 1)
    {
      this.focus1.nativeElement.focus();
    }else{
      this.focus2.nativeElement.focus();
    }
  }
}

Run the app, make sure the app works correctly as the next gif

Focus Function Input Boxes Angular 4

Read another article: Angular 4 Tutorial For Beginner With Simple App Project

If you need a complete autofocus directive file, you can download it from the following link. To open the download link, share this article through social media account using the button below.

[sociallocker id=58]

URL : https://seegatesite.com/create-autofocus-directive-angular-4-example-project-download/

Password : seegatesite.com

[/sociallocker]

So my article on focus on element directive in angular 4, may be useful

Another Javascript Related Post :

  • React-Table Not Updating or Refreshing Data, The Solution ?
  • How To Custom React Datepicker In Bootstrap
  • Tutorial Create Simple POS Using ReactJS And Laravel Lumen Part 1
  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Comments

  1. Avatar for WandyatmonoWandyatmono says

    April 18, 2018 at 3:20 pm

    The routing and AutofocusDirective failed!.

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      April 19, 2018 at 7:06 am

      working perfectly in my project. Whould you show to me the error message?

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) lumen api (4) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (8) Publisher Tips (5) react (6) Reactjs (9) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2022 Seegatesite.com