0

For some reason I can't get the value of the list element in the html despite using document.getElementByID and it has the same id. It claims that the element is undefined. Here is the code:

fileupload.component.ts:

ngOnInit() {  
  var x = document.getElementById('lemons'); 
  if(x){
    console.log('it does exits')
    x.addEventListener('click', function(e:any){
      console.log(x.innerHTML);
    });
  }
}

fileupload.component.html:

<div class="row" id="filesDisplay">
<div class="col-md-4" id="files">
    <li *ngFor="let child of tree" id="lemons">
            {{child}}
    </li>
</div>
3
  • 1
    You could consider using template-variable with ViewChildren, bind click listner directly using (click)="myEvent($event)" Commented Jan 25, 2018 at 11:44
  • 1
    angular.io/guide/template-syntax Commented Jan 25, 2018 at 11:46
  • 1
    Your template is incorrect: each <li> element (representing a separate element of tree list) has the same id - 'lemons'. Commented Jan 25, 2018 at 11:49

2 Answers 2

3

The *ngFor directive is processed after the OnInit hook, so if you want to get an element generated with the *ngFor you should use:

ngAfterViewInit() { }

Also you are duplicating the id, this means it only will select the first element.

lifecycle-hooks angular's guide

Edit: added angular guide

Sign up to request clarification or add additional context in comments.

2 Comments

This worked to register clicks but only prints the first element.
Yes because you are using the same id for all the <li> elements. So when you are printing the <li> innerHTML it only has the first one.
2

You can not repeat same html id for all the li's. You need to add index to id to diffrentiate.

 <div class="row" id="filesDisplay">
  <div class="col-md-4" id="files">
   <li *ngFor="let child of tree" (click)="test(child)">
        {{child}}
   </li>
</div>

and in javascript you need to pull the id accordingly.

  ngOnInit() {  
   test(res) {
     // perform your logic here..
    } 
}

You no need to use jquery here where angular is providing all your need in DOM manipulation.

2 Comments

what would I do if i wanted the item that they clicked on
This worked perfectly, however I didn't put it in the ngOnInit. I put it on the outside instead.

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.