我在angular2 app中使用带占位符的输入字段。
<input #searchEl type="search" placeholder="some text" autofocus>
要求是默认情况下将焦点放在输入字段上。但是在IE上,看起来我们关注时不会显示占位符文本(不是chrome和firefox的情况)。
此问题是否有任何解决方案或解决方法?当我们关注IE上的输入字段时,有没有办法显示占位符文本?我正在使用IE 11
答案 0 :(得分:0)
您应该使用renderer2
库来操作DOM以获得最佳实践。如果focus
不起作用,请尝试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');
}
}`
您也可以通过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>`