![](/img/trans.png)
[英]angular2 - How to DOM select a dynamically created element and focus it?
[英]How to select dom element in a loop in angular 5
我是新手,並且每天都在學習它。 我正在用角度5作曲,結果進展順利。 我只是陷入一個小問題,我可以使用jquery解決這個問題,但是我想以有角度的方式解決它。
這是我的粗魯
默認情況下,輸入框是禁用的,我想要的是,當我單擊“編輯”時,它應該啟用,而我只需要啟用相鄰輸入而不是全部。
到目前為止,這是我嘗試過的。
home.component.html
<div class="container color-dark">
<div class="col">
<p>Add a bucket list item</p>
</div>
<div class="col">
<p>Your bucket list ({{itemscount}})</p>
</div>
</div>
<div class="container color-light">
<div class="col">
<p class="sm">Use this form below to add a new bucket list goal. What do you want to accomplish in your life?</p>
<form>
<input type="text" class="txt" name="item" placeholder="{{goalText}}" [(ngModel)]="goalText">
<br><span>{{ goalText }}</span><br>
<input type="submit" class="btn" [value]="btnText" (click)="additem()">
</form>
</div>
<div class="col">
<p class="life-container" *ngFor = "let goal of goals; let i = index" >
<input type="text" value=" {{ goal }}" [disabled]="editable" #goalInput>
<span class="edit_btn" (click)="edititem(i)">{{edit_btn_txt}}</span>
<span class="delete_btn" (click)="removeitem(i)">Delete</span>
</p>
</div>
</div>
這是我的打字稿文件代碼
import { Component, ViewChild, AfterViewInit, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
itemscount:Number = 0;
btnText:string="Add an Item";
goalText:string = "";
goals = ['My First Goal'];
editable:Boolean = true;
edit_btn_txt:string = "Edit";
constructor() { }
ngOnInit() {
}
@ViewChild('goalInput') pizzaInput: ElementRef;
additem(){
this.goals.push(this.goalText);
this.goalText='';
this.itemscount = this.goals.length;
}
ngAfterViewInit() {
//console.log(this.extraIngredient); // tomato
}
edititem(i){
this.pizzaInput.nativeElement.disabled = false;
}
removeitem(i){
this.goals.splice(i,1);
this.itemscount = this.goals.length;
}
}
當我單擊“編輯”按鈕時,第一個框已啟用寫入功能,但它已經工作了一段時間。 它不適用於其他盒子。 我該如何處理?
提前致謝。
這是使用ViewChildren的另一種解決方案:
@ViewChildren('goalInput') pizzaInput;
edititem(i){
this.pizzaInput.toArray()[i].nativeElement.disabled = false;
}
嘗試這個
<p class="life-container" *ngFor = "let goal of goals; let i = index" >
<input type="text" value=" {{ goal }}" [disabled]="i != selectedIndex" #goalInput>
<span class="edit_btn" (click)="edititem(i)">{{edit_btn_txt}}</span>
<span class="delete_btn" (click)="removeitem(i)">Delete</span>
</p>
並在您的component.ts中添加此
selectedIndex: number;
constructor() {
this.selectedIndex = -1;
}
edititem(i){
this.selectedIndex = i;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.