Search code examples
javascriptangularcomponents

How to select dom element in a loop in angular 5


I am a newbie in angular and just learning it day by day. I am making a crud in angular 5 and it is going good. I am just stuck in a little problem which I can solve using jquery but I want to solve it in angular way.

This is my crud

enter image description here

The input box is disabled by default what i want is that when I click on "Edit" it should enable and I need to enable only the adjacent input not all.

This is what I have tried so far.

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>

This is my typescript file code

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;
    }
}

When I click on the edit button the first box is enabled for writing but it is working for one time. It is not working for other boxes. How can I handle this problem ?

Thanks in advance.


Solution

  • here is another solution by using ViewChildren:

    @ViewChildren('goalInput') pizzaInput;
    
    edititem(i){
      this.pizzaInput.toArray()[i].nativeElement.disabled = false;
    }