You should use renderer2
library in order to manipulate DOM for best practices. If focus
doesn't work try also click
`import { Component, ElementRef, ViewChild, AfterViewInit, Renderer2 } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<input #searchEl (focus)="keepPh()" type="search" placeholder="some text">
<div> Some other content </div>
`
})
export class ChildComponent implements AfterViewInit {
@ViewChild('searchEl') input: ElementRef;
constructor(private renderer: Renderer2) { }
//Sets autofocus true when component's views are initialized
ngAfterViewInit() {
this.renderer.setProperty(this.input.nativeElement, 'autofocus', true);
}
//Keeps place holder visible on input focus
keepPh() {
this.renderer.setAttribute(this.input.nativeElement, 'placeholder', 'some text');
}
}`
You can also do this via directives
`import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appFocus]'
})
export class FocusDirective {
constructor(private renderer: Renderer2, private el: ElementRef) { }
toggleFlag: Boolean = false;
ngOnInit() {
this.renderer.listen(this.el.nativeElement, 'focus', () => {
this.toggleFlag = (this.toggleFlag === true) ? false : true;
if (this.toggleFlag) {
this.renderer.setAttribute(this.el.nativeElement, 'placeholder', 'some text');
} else {
this.renderer.removeAttribute(this.el.nativeElement, 'placeholder', 'some text');
}
})
}
}
//Use it like so:
<input type="search" placeholder="some text" appFocus>`