Ionic 3 - Add Rows Dynamically with ion-select using new component


#1

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { InputRowComponent } from './input-row/input-row.component'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  // will hold data for the elements added to the form
  inputRowValues = [{}]

  
  constructor(public navCtrl: NavController) { }

  // adds new entry into the inputRowValues array
  addRow() {
    this.inputRowValues.push({})
  }

  // removes entry from the  inputRowValues array based on the id
  onDelete(_event) {
    console.log(_event)
    this.inputRowValues = this.inputRowValues.filter((i: any) => i.id !== _event.id)
  }

}

home.html

	<div padding>
		<button ion-button (click)="addRow()" block >Add New Row Item</button>
    <div padding>Swipe Row Items To Delete...</div>
  </div>

  <ion-list>
    <div *ngFor="let i of inputRowValues; let ii=index"  style="font-size:smaller">
      <app-input-row [data]="i" (onDelete)="onDelete($event)"></app-input-row>
    </div>
  </ion-list>

input-row.component.ts

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-input-row',
  templateUrl: './input-row.component.html',
  styleUrls: ['./input-row.component.css']
})
export class InputRowComponent implements OnInit {

  // the data object to hold values from this component
  @Input() data: any

  // emitt an event to indicate the user has clicked on 
  // the delete button in this component
  @Output() onDelete = new EventEmitter<any>();

  // constructor
  constructor() {
  }

  // when the component is created, add a unique id
  // to the data so we can find it when deleting
  ngOnInit() {
    this.data.id = new Date().getTime()
  }

  // when the delete button has been clicked, emitt an event
  // that includes the object that was clicked on
  deleteClicked() {
    console.log("deleteClicked")
    this.onDelete.next(this.data)
  }
}

input-row.component.html

<ion-item-sliding>
	<ion-item>
		<ion-label>Comp├ętence {{index}}</ion-label>
		<ion-select [(ngModel)]="data.value">
			<ion-option value="informatique">Informatique</ion-option>
			<ion-option value="jardinnage">Jardinnage</ion-option>
			<ion-option value="impression3D">Impression 3D</ion-option>
			<ion-option value="menuiserie">Menuiserie</ion-option>
			<ion-option value="secouriste">Secouriste</ion-option>
			<ion-option value="montagevideo">Montage Video</ion-option>
			<ion-option value="excel">Excel</ion-option>
			<ion-option value="word">Word</ion-option>
			<ion-option value="sharepoint">Sharepoint</ion-option>
			<ion-option value="soudeur">Soudeur</ion-option>
		</ion-select>

	</ion-item>
    <ion-item-options side="right">
      <button ion-button color="danger"  (click)="deleteClicked(item)">DELETE</button>
    </ion-item-options>
</ion-item-sliding>