1

I want to get the value of a div located inside a <form> the content of that div can be changed by the user as that div outputs a particular value (number of items in a shopping cart, the user can add, reduce the quantity of a certain item in that cart).

What I want to do is to get the value of that div, eg. in JavaScript we are doing something like that:

document.getElementById("idOfDiv").innerHTML

I want to do the exact same thing in Angular 2

P.S. My Angular 2 project is based on JS

Currently I have:

<div #nbOfItems>{{ (items()) }}</div>
Folky.H
  • 1,164
  • 4
  • 15
  • 37
  • can you use `#myDiv` over template element, and access that variable in component class? – Pankaj Parkar Jul 11 '16 at 16:16
  • I guess so, can you please give an example? – Folky.H Jul 11 '16 at 16:22
  • before that could you add some code here? – Pankaj Parkar Jul 11 '16 at 16:23
  • I've added what I have so far, which code you want me to add? – Folky.H Jul 11 '16 at 16:26
  • I understand you might be in a situation that requires this approach but for other AngularJS users I strongly suggest you rethink your app, any data you need should ideally be represented in an internal state/data object. For instance the more Angular-friendly approach would be to store the shopping cart as a Javascript object and bind its different values to the DOM, but using the data as a base for manipulation/reading. – kb. Jul 11 '16 at 16:56

1 Answers1

3

You can access the Element via ElementRef in your component:

import {ElementRef, OnInit} from '@angular/core';

ngOnInit() {
 var el = this.element.nativeElement;
 console.log(el);
}

or with ViewChild:

import {ViewChild} from '@angular/core';

@ViewChild('nbOfItems') nbOfItems; 

ngAfterViewInit() {
  console.log(this.nbOfItems.nativeElement.value);
}
muetzerich
  • 5,600
  • 7
  • 37
  • 52
  • I receive a syntax error: `Missing class properties transform.` Maybe that's only valid in TypeScript – Folky.H Jul 11 '16 at 17:36
  • the code should work. This is a babel error i think. Take a look here maybe this helps you: https://stackoverflow.com/questions/35517245/error-missing-class-properties-transform – muetzerich Jul 11 '16 at 17:41
  • The second one, worked for me, but with this notation : `queries: { nbOfItems: new ViewChild('nbOfItems') }` – Folky.H Jul 11 '16 at 19:06