Muhammad Hunain
Muhammad Hunain

Reputation: 13

add div of two select tags on a button in angular?

I am new to angular. I am using typescript. I want to achieve this task.

Here is the image of what I want do.

I want to add the date and location selector on add button click. I actually did that but I am unable to maintain its data when I remove its row.

Here is what I did in html:

 <div id="" *ngFor = "let sp of specialityElementCount">
                <select id="specialityDate"
                        class="textField"(change)='selectSpecialityDate($event.target.value)'>
                <option>Select Date</option>
                <option *ngFor = "let date of spDates" 
                        [value]="date">{{date}}</option>
                </select>

                <select class="textField"
                        [ngClass]="{'specialityLocation':(sp=='speciality1'),'specialityLocationRemove':(sp!='speciality1')}"
                        (change)='selectSpecialityLocation($event.target.value, sp)'>
                <option>Select Location</option>
                <option *ngFor = "let location of specialityLocation" 
                        [value]="location">{{location}}</option>
                </select>
                
                <div class= "removeImgDiv"[hidden]="sp=='speciality1'">
                         <img class="removeImg" (click)="removeRow(sp)" src="../../assets/img/remove.png">
                </div>
        </div>

and here is what I did in typescript:

 specialityElementCount = ["speciality1"];

addRow(row:string){
    console.log(row);
    if(row.includes("speciality")){
      this.specialityElementCount.push("speciality"+(this.specialityElementCount.length+1));
    }
  }
  removeRow(row){
    console.log(row);
    if(row.includes("speciality")){
      this.specialityElementCount.splice(this.tripLocations.indexOf(row), 1);
    }
  }

  selectSpecialityDate(event){
    console.log(event);
  }
  selectSpecialityLocation(event, text){
    console.log(event);
    console.log(text);
  }

Please help me with this. That when I remove row it removes the correct row instead of remove the last row every time.

Thanks in advance.

Upvotes: 1

Views: 197

Answers (1)

toskv
toskv

Reputation: 31612

What you can do use the index generated by *ngFor instead of searching for the row yourself.

It would look something like this:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div *ngFor="let row of data; let index = $index">
        <div>{{row}}</div>
        <div (click)="removeRow(index)">X</div>
      </div>
    </div>
  `,
})
export class App {
  data:string[];
  constructor() {
    this.data = ['a', 'b','c']
  }

  removeRow(index) {
    this.data.splice(index, 1);
  }
}

You can see a working plunkr with the example here.

Upvotes: 1

Related Questions