Ответ 1
Это мой текущий код:
import { Directive, ElementRef, Input } from "@angular/core";
@Directive({
selector: "[autofocus]"
})
export class AutofocusDirective
{
private focus = true;
constructor(private el: ElementRef)
{
}
ngOnInit()
{
if (this.focus)
{
//Otherwise Angular throws error: Expression has changed after it was checked.
window.setTimeout(() =>
{
this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
});
}
}
@Input() set autofocus(condition: boolean)
{
this.focus = condition !== false;
}
}
вариант использования:
[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus
Устаревший код (старый ответ, на всякий случай):
Я получил этот код:
import {Directive, ElementRef, Renderer} from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class Autofocus
{
constructor(private el: ElementRef, private renderer: Renderer)
{
}
ngOnInit()
{
}
ngAfterViewInit()
{
this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
}
Если я добавлю код в ngOnViewInit
, он не будет работать. В коде также используются лучшие практики, поскольку не рекомендуется recommended вызывать фокус на элементе напрямую.
Отредактировано (условный автофокус):
Несколько дней назад мне потребовался условный автофокус, потому что я скрываю первый элемент автофокуса и хочу сфокусировать другой, но только когда первый элемент не виден, и я закончил следующим кодом:
import { Directive, ElementRef, Renderer, Input } from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class AutofocusDirective
{
private _autofocus;
constructor(private el: ElementRef, private renderer: Renderer)
{
}
ngOnInit()
{
}
ngAfterViewInit()
{
if (this._autofocus || typeof this._autofocus === "undefined")
this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);
}
@Input() set autofocus(condition: boolean)
{
this._autofocus = condition != false;
}
}
Edited2:
Renderer.invokeElementMethod устарел, и новый Renderer2 не поддерживает его.
Итак, мы вернулись к исходному фокусу (который не работает вне DOM - например, SSR!).
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[autofocus]'
})
export class AutofocusDirective
{
private _autofocus;
constructor(private el: ElementRef)
{
}
ngOnInit()
{
if (this._autofocus || typeof this._autofocus === "undefined")
this.el.nativeElement.focus(); //For SSR (server side rendering) this is not safe. Use: https://github.com/angular/angular/issues/15008#issuecomment-285141070)
}
@Input() set autofocus(condition: boolean)
{
this._autofocus = condition != false;
}
}
вариант использования:
[autofocus] //will focus
[autofocus]="true" //will focus
[autofocus]="false" //will not focus