1

I'm trying to insert HTML Input Element on button click inside div container. I have created a directive & added the directive on the child input elements. Whenever I click on the input element, that element should be removed from the DOM.

I'm able to achieve this behavior but whenever I click on one HTML Input Element, then all the HTML Elements are removed from the DOM which is not expected.

So, How to get single html input elementref in directive ? app.component.html

<div class="btn-container">
  <button (click)="addInputElement()">Add Input</button>
</div>
<div class="box-container">
    <input deleteDir *ngFor="let el of inputEl; let i = index" id={{i}} [value]=el.value>{{el.value}}/>
</div>

app.component.ts

export class AppComponent implements OnInit{
   inputEl = [];
   addInputElement() {
     this.inputEl.push({value: Math.random()});
   }
}

app.directive.ts

constructor(private elementRef: ElementRef, 
            private renderer: Renderer2) { }


@HostListener('click') onClick() {
    this.renderer.removeChild(this.elementRef.nativeElement.parentNode,this.elementRef.nativeElement)
}
2
  • Where you are applying the directive in your component? Commented Oct 27, 2020 at 7:29
  • @Obaid I have updated the input html tag. The directive is deleteDir Commented Oct 27, 2020 at 8:00

1 Answer 1

1

I recreated your use case and the code you provided looks fine to me. I've created a StackBlitz for it, you can check this out. When I click on one input element, only the one I clicked gets removed.

Update

I have updated my StackBlitz from above. Now the input fields get deleted one by one if you press a key. Basically what I have done is to pass an index to the directive

HTML

<...>
    *ngFor="..."
    delete      <-- directive
    [index]="i" <-- input parameter in directive
</...>
DIRECTIVE

@Input()
index: number;

constructor(private elementRef: ElementRef, private renderer: Renderer2) {}

@HostListener("input")
onInput() {
   this.renderer.removeChild(
    this.elementRef.nativeElement.parentNode,
    this.elementRef.nativeElement.parentNode.querySelector(
      `[id="${this.index}"]`
    )
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You ! Yes working for Input element, but for keypress event all the child divs are getting removed from DOM. I mean, If I select the particular div and click on delete button , then all the child divs are removed. Why is this happening ?
Ah you are talking about they keypress, let me check that as well. You should update your initial question, as keypress was not part of it.
I have adapted by example, it now works with any event being done in the input field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.