Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Directive, Input, ElementRef} from 'angular2/core';
- @Directive({
- selector: '[focus]'
- })
- class FocusDirective {
- @Input()
- focus:boolean;
- constructor(@Inject(ElementRef) private element: ElementRef) {}
- protected ngOnChanges() {
- this.element.nativeElement.focus();
- }
- }
- // Usage
- @Component({
- selector : 'app',
- template : `
- <input [focus]="inputFocused" type="text">
- <button (click)="moveFocus()">Move Focus</button>
- `,
- directives: [FocusDirective]
- })
- export class App {
- private inputFocused = false;
- moveFocus() {
- this.inputFocused = true;
- // we need this because nothing will
- // happens on next method call,
- // ngOnChanges in directive is only called if value is changed,
- // so we have to reset this value in async way,
- // this is ugly but works
- setTimeout(() => {this.inputFocused = false});
- }
- }
- import { Directive, ElementRef, Renderer, AfterViewInit } from '@angular/core';
- @Directive({
- selector: '[focus]'
- })
- export class DmFocusDirective implements AfterViewInit {
- constructor(private _el: ElementRef, private renderer: Renderer) {
- }
- ngAfterViewInit() {
- this.renderer.invokeElementMethod(this._el.nativeElement, 'focus');
- }
- }
- this.renderer.invokeElementMethod(this.input.nativeElement, 'focus', []);
- import { Directive, ElementRef, Renderer} from "@angular/core";
- @Directive({
- selector: "[Focus]"
- })
- export class myFocus {
- constructor(private _el: ElementRef, private renderer: Renderer) {
- this.renderer.invokeElementMethod(this._el.nativeElement, 'focus');
- }
- }
- import {Directive, AfterViewInit, ElementRef, DoCheck} from '@angular/core';
- @Directive({selector: '[focus]'})
- export class FocusDirective implements AfterViewInit, DoCheck {
- private lastVisible: boolean = false;
- private initialised: boolean = false;
- constructor(private el: ElementRef) {
- }
- ngAfterViewInit() {
- console.log('inside FocusDirective.ngAfterViewInit()');
- this.initialised = true;
- this.ngDoCheck();
- }
- ngDoCheck() {
- console.log('inside FocusDirective.ngDoCheck()');
- if (!this.initialised) {
- return;
- }
- const visible = !!this.el.nativeElement.offsetParent;
- if (visible && !this.lastVisible) {
- setTimeout(() => {
- this.el.nativeElement.focus();
- }, 1);
- }
- this.lastVisible = visible;
- }
- }
- const element = this.renderer.selectRootElement('#elementId');
- element.focus();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement