[英]Angular focus on input while clicking an element
我已經附上了下面的stackblitz
https://stackblitz.com/edit/angular-dgx3pe
我想要實現的是點擊標簽元素時它應該集中在輸入上。因此輸入:焦點類被激活。我相信它可以通過javascript / jquery實現。但我更喜歡有角度的方式來實現這一點。
簡而言之,這些是我想要做的兩件事,
HTML
<input class="input" type="text">
<label class="label">Name</label>
<div>
<input class="input" type="text">
<label class="label">Name</label>
</div>
CSS
p {
font-family: Lato;
}
.input
{
border:none;
border-bottom:1px solid grey;
outline:none;
margin-top:20%;
}
.input:focus
{
border-bottom:1px solid orange;
}
.label
{
position:relative;
left:-170px;
}
.input:focus + .label
{
bottom:20px;
}
您可以使用純標記執行此操作。 您需要在輸入中添加id,為標簽添加for元素
<input class="input" type="text" id="firstName">
<label class="label" for="firstName" >First Name</label>
這只是html規范的一部分 - 標簽可以與輸入相關聯 - 此處的開箱即用功能是單擊標簽時將焦點設置為其關聯輸入。 id和for屬性必須匹配才能生效。
對於問題的第二部分,並重用您的css類 - 將匹配的變量添加到您的組件。 當變量具有值時,使用ngClass添加.go-top類
在組件中 -
firstName: string;
然后在HTML中 -
<input class="input" type="text" id="firstName" [(ngModel)]="firstName">
<label class="label" for="firstName" [ngClass]="{'go-top': firstName}">First Name</label>
<input #firstNameField class="input" type="text">
<label class="label" (click)="focusOnFirstName()">First Name</label>
@ViewChild("firstNameField") firstNameField;
focusOnFirstName(){
this.firstNameField.nativeElement.focus();
}
我從為條件樣式請求制作更“Angular”解決方案的角度來看這個。 為此,您應該專注於將輸入/標簽組合滾動到自定義輸入組件中。 使用原始元素作為起始模板創建組件后,您可以更有效地制定以下內容。
基本策略是使用Angular的[class]屬性綁定或[NgStyle]指令有條件地應用您的樣式。
<input>
字段值並更新表示字段是否為空的class屬性 //component.ts
import { Component, Input, ViewChild, ElementRef } from '@angular/core'
@Component({
selector: 'app-input',
styleUrls: ['./input.component.css'],
templateUrl: './input.component.html'
})
export class InputComponent{
@Input() labelName: string = "Your Label Here"
@ViewChild("input") myInput:ElementRef<any> //ViewChild query
empty: Boolean = true; // this property will track whether input value is truthy
isEmpty(){ // attached to keyup event on input element in your template file
if (this.myInput.nativeElement.value){
this.empty = false;
} else{
this.empty = true;
}
}
styles(){ // attached to the [ngClass] directive binding on input element in template file
return {
'empty': this.empty ? true: false,
'not-empty': this.empty ? false: true
}
}
}
//component.html with [ngClass] directive
<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [ngClass]="styles()" (keyup) = "isEmpty()" #input>
//component.html with [style] property binding
// in this instance, empty is a reference to the property in the .ts file
<label for="my-input" #label> {{ labelName }}
<input type="text" id="my-input" [class.empty]="empty" #input>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.