title: Angular 4 - How to get the index of $event.currTarget from the ViewContainerRef
body: <p><strong>What Am I trying to accomplish</strong>:
  When the user press <code>enter</code> inside a <code>&lt;p&gt;</code> element, a new <code>&lt;p&gt;</code> element is added right after it. <strong>it is possible that the user press the ENTER key on the 5th out o 70 views...</strong></p>
  
  <p><strong>How Am i trying to do it</strong>: On the <code>&lt;p&gt;</code> element, there is a <code>keyPress</code> Listener. When the <code>enter</code> key is pressed, I am trying to get the index of the current element and add one right after as follows:</p>
  
  <pre><code>let dom_view = e.currentTarget
  let index = this.richtextbox.indexOf(dom_view);
  
  this.richtextbox.insert(this.p_dom.createEmbeddedView(null),index+1);
  </code></pre>
  
  <p><strong>The issue i am facing</strong>: index is always -1 as e.currentTarget (same as e.target) is not identified by the container! What is the right way to get the index?</p>
  
  <p><strong>My Component code is</strong>:</p>
  
  <pre><code>import {
    AfterViewInit, Component, ViewChild, ViewContainerRef
  } from '@angular/core';
  
  @Component({
    selector: 'app-editor',
    templateUrl: './editor.component.html',
    styleUrls: ['./editor.component.css']
  
  })
  export class EditorComponent  implements AfterViewInit {
  
    @ViewChild('richtextbox', {read: ViewContainerRef}) richtextbox: ViewContainerRef;
    @ViewChild('p_dom') p_dom;
  
    ngAfterViewInit(): void {
      // insert a p element
      let view1 = this.p_dom.createEmbeddedView(null)
      this.richtextbox.insert(view1);
    }
    editor_keypress(e) {
      let dom_view = e.currentTarget
  
      if (e.key === 'Enter') {
        let index = this.richtextbox.indexOf(dom_view);
        // notice that index is the index of the view that the user pressed
        // the enter on. there can be 1000 views... and i want to add the new 
        // view right after the one that the user pressed the enter on
        console.log('index = ', index)
  
        this.richtextbox.insert(this.p_dom.createEmbeddedView(null),index+1);
      }
    }
  }
  </code></pre>
  
  <p>The HTML context is:</p>
  
  <pre><code>&lt;ng-container #richtextbox&gt;
  &lt;/ng-container&gt;
  
  &lt;ng-template #p_dom&gt;
    &lt;p contenteditable="true" (keypress)="editor_keypress($event)"&gt;I am editable test message&lt;/p&gt;
  &lt;/ng-template&gt;
  </code></pre>
  
  <h2>Update</h2>
  
  <p>I ended up using <code>Renderer2</code>in order to manipulate the doms. The problem with the ViewRef is that i wasn't able to create Listenner with closure to the view as Described by  Bougarfaoi's Answer. If you want to have a look at the code, here is a <a href="https://github.com/exhesham/electron-markdown-editor/tree/master/src/app" rel="nofollow noreferrer">link</a> to the github code.</p>