我正在尝试使用Anuglar 2创建一个输入文本字段,该字段应如下图所示:
我有一个类.tn_blue,当元素处于焦点时,我希望将其添加到div(下面的粗体)中。
我无法使用组件上的主机绑定焦点:
我的代码:
import {Component, ElementRef, Renderer, Input, OnInit} from '@angular/core';
@Component({
selector : 'my-textfield',
templateUrl : 'path-to/textfield.component.html',
styleUrls : ['path-to/textfield.component.css'],
host: {
'(focus)':'_setInputFocus(true)',
}
})
export class Textfield implements OnInit{
@Input() iconBoxTextfieldConfig:any;
inputFocusClass: boolean;
_setInputFocus(isFocus:boolean) {
this.inputFocusClass = isFocus;
console.log("he he he ")
}
elementRef: ElementRef;
constructor(private el: ElementRef, public renderer: Renderer) {
this.elementRef = el;
}
ngOnInit(){
this.inputFocusClass = true;
}
}
HTML code:
<div class="tn-formfield" *ngIf="iconBoxTextfieldConfig">
<div class="tn-inline tn-label">
<span *ngIf="iconBoxTextfieldConfig.isRequired" class="tn-asterisk">*</span>
<span class="tn-label">{{iconBoxTextfieldConfig.label}}:</span>
</div>
**<div class="tn icon-icon_Edit" [class.tn-focus]:'inputFocusClass'>
<!-- <span class="tn icon-icon_Edit"></span> -->
<input [style.width] = "iconBoxTextfieldConfig.width" class="tn-icon-textfield" [disabled]="iconBoxTextfieldConfig.isDisabled">
<div class="tn-icon-hintText">{{iconBoxTextfieldConfig.hintText}}</div>
</div>**
</div>
scss代码
.tn_focus {
outline:1px solid blue;
border: none;
color:#FFF;
background-color: blue;
}
任何建议都将不胜感激
答案 0 :(得分:4)
import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';
@Directive({
selector: '[onFocus]',
})
export class OnFocusDirective {
private el: ElementRef;
constructor(private _el: ElementRef, public renderer: Renderer) {
this.el = this._el;
}
@HostListener('focus', ['$event']) onFocus(e) {
this.renderer.setElementClass(this._el.nativeElement, 'tn_focus', true);
return;
}
@HostListener('blur', ['$event']) onblur(e) {
this.renderer.setElementClass(this._el.nativeElement, 'tn_focus', false);
return;
}
}
在元素上使用此指令onFocus(您要在其上添加类)
答案 1 :(得分:2)
这似乎是一个错字
[class.tn-focus]:'inputFocusClass'
应该是
[class.tn-focus]='inputFocusClass'
除此之外应该这样做
<input
(focus)="inputFocusClass = true"
(blur)="inputFocusClass = false; null"
[style.width] = "iconBoxTextfieldConfig.width" class="tn-icon-textfield" [disabled]="iconBoxTextfieldConfig.isDisabled">
结果为; null
(false
)的内联代码需要inputFocusClass = false
,因为这会导致在事件中调用preventDefault()
。附加; null
只是将表达式的返回值更改为null
。 true
事件处理程序中的返回值(focus)
没有任何效果,因为它是默认行为。