Angular中的JavaScript |事件绑定

时间:2018-05-14 16:29:46

标签: javascript html angular

我有一个Twitter Bootstrap表单,当它成为焦点时会获得橙色边框底部。但是输入行上的图标有自己的border-bottom,我不知道如何将Angular中的焦点事件绑定到使图标的border-bottom也为橙色的函数。

<form>
    <div class="form-group">
        <div class="input-group">
            <div class="input-group-prepend">
                <div class="input-group-text" id="emailInputIcon"><i class="fal fa-envelope"></i></div>
            </div>
            <input type="email" class="form-control" id="emailInputLogin" aria-describedby="emailHelp" placeholder="EMAIL">
        </div>
     </div>
     <div class="form-group">
         <div class="input-group">
             <div class="input-group-prepend">
                 <div class="input-group-text" id="passwordInputIcon"><i class="fal fa-key"></i></div>
             </div>
             <input type="password" class="form-control" id="passwordInputLogin" placeholder="PASSWORD">
         </div>
     </div>
 <button type="submit" class="btn btn-primary">Login</button>
</form>

1 个答案:

答案 0 :(得分:2)

简单方法就像这样(为了便于阅读而简化):

HTML:

<input (focus)="onInputFocused()" (blur)="onInputBlurred()" />
<div class="icon" #icon></div>

TS:

@ViewChild('icon') icon: ElementRef;

onInputFocused() {
    this.icon.nativeElement.style.borderBottom = 'orange 1px solid';
}
onInputBlurred() {
    this.icon.nativeElement.style.borderBottom = '';
}

更优雅:

HTML:

<input (focus)="onInputFocused()" (blur)="onInputBlurred()" />
<div class="icon" [ngClass]={'withBorder': focused}></div>

TS:

focused = false;
onInputFocused() {
    this.focused = true;
}
onInputBlurred() {
    this.focused = false;
}

CSS:

.withBorder {
    border-bottom: orange 1px solid;
}

没有Angular,一个普通的CSS解决方案(最好):

HTML:

<div class="has-input">
    <input type="text" />
    <div class="icon"></div>
</div>

CSS:

.has-input input:focus + .icon {
    border-bottom: orange 1px solid;
}