* ngIf with focus

In my application, I tried to place a button that shows / hides the field inputwith the booleancomponent property. If the button shows input, the focus should be set to input. But it doesn't seem to work. If I *ngIffocus directive works fine.

I created a piston that shows what I mean. It is hard to describe my problem.

HTML in component:

<input *ngIf="filterShow.options"
       [focus]="filterFocus.options"
       [(ngModel)]="filter.options">

<button type="button"
        (click)="setShowFilter('options')">
  focus
</button>

setShowFilter() :

private setShowFilter(filter: string) {
  this.filterShow[filter] = !this.filterShow[filter];

  /* reset filter */
  this.filter[filter] = "";

  this.filterFocus[filter].emit(true);
}

focus.directive.ts :

@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnInit {

  @Input('focus') focusEvent: EventEmitter<boolean>;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnInit() {
    this.focusEvent.subscribe(event => {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    });
  }
}
+7
source share
3 answers

EventEmitterare for @Outputs, not @Inputs. Try something like this:

@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnChanges {

  @Input('focus') focus: boolean;

  constructor(private elementRef : ElementRef,
              private renderer   : Renderer   ) { }

  ngOnChanges() {
    if (this.focus) {
      this.renderer
        .invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
    }
  }
}
+8
source

, . , . setTimeout, :

import { Directive, OnChanges, Input, ElementRef } from "@angular/core";

@Directive({
  selector: '[focus]'
})
export class FocusDirective implements OnChanges {
  @Input('focus') focus: boolean;

  constructor(private elementRef : ElementRef) { }

  ngOnChanges() {
    if (this.focus) {
      setTimeout(() => { this.elementRef.nativeElement.focus(); }, 0);      
    }
  }
}
+2

- <label> <button> css . ,

<label for="myInput"></label> <input id="myInput"></input>

, *ngIf, <input> <label>. , Angular2 ElementRef - , .

0

Source: https://habr.com/ru/post/1673738/


All Articles