Reputation: 3619
I need to duplicate a new row on the click of +
button. That new row contains a -
button which will in turn delete that newly created row. So the problem is I could attach a click event to that new -
button.
Below is the ts which contains the form :
import { Component, OnInit, ViewEncapsulation, ElementRef } from '@angular/core';
import { MailSegmentObject } from './mailSegmentObject';
import { MailSegmentRule } from './mailSegmentRule';
@Component({
selector : 'segment-form',
templateUrl : 'app/html/createSegment.html',
styleUrls : ['node_modules/bootstrap/dist/css/bootstrap.min.css'],
encapsulation : ViewEncapsulation.Native
})
export class CreateSegmentComponent {
counter : number = 0;
segment : MailSegmentObject = new MailSegmentObject();
addNewRule() : void {
var origElem = document.getElementById("mandatoryRule");
var copyElem = <HTMLDivElement>origElem.cloneNode(true);
copyElem.setAttribute("id", "mandatoryRule_" + (this.counter++));
copyElem.innerHTML += "<div class=\"col-sm-1\"><button type=\"button\" class=\"btn btn-default\" (click)=\"deleteRule(this)\">-</button></div>";
origElem.parentElement.appendChild(copyElem);
}
deleteRule(elem) : void {
console.log("asdasdasdasdasd");
elem.parentElement.removeChild(elem);
}
}
and html is:
<div class="container" style="margin-top: 15px;">
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="Segment Name">Segment Name</label>
<div class="row">
<div class="col-sm-12">
<input type="text" class="form-control" id="segmentNameInput" placeholder="Segment Name">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Select Property</label>
<div class="row rule" id="mandatoryRule">
<div class="col-sm-3">
<select class="form-control">
</select>
</div>
<div class="col-sm-3">
<select class="form-control">
</select>
</div>
<div class="col-sm-3">
<input type="text" class="form-control">
</div>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-default" (click)="addNewRule(this)">+</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
Kindly help me out. Thanks.
Upvotes: 0
Views: 66
Reputation: 71931
This is written completely against the concept of angular2. You should use *ngFor
on a collection of lines
. Never ever -ever- use things like: getElementById
, cloneNode
, innerHTML
, appendChild
, removeChild
.
My suggestion is that you take a closer look to the tutorials and cook book provided at angular.io, because I'm sorry, with the current state of your code, you are asking for a complete rewrite
Upvotes: 1