2

Angular 4 change event is working fine with input type text which is as below

<input type="text" (change)="updateData($event)"/>

but when we write code as below then It does't work.

<span id="fname" (change)="updateData($event)"></span>

Can anyone give me litter insight for this behavior and If possible then best way to achieve the same.

Jyotish Singh
  • 2,065
  • 3
  • 20
  • 28
  • 4
    How do you expect that a non-interactive element is firing a `change` Event? A change event is only fired if the user's input changes. For example typing something in an input element. – cyr_x Aug 01 '17 at 10:33
  • I am making contenteditable="true" for span. – Jyotish Singh Aug 01 '17 at 10:37
  • What prevents you from just using an input ? You're trying to force some functionallity on a poor little `span` element, which isn't there for such a strong task. – cyr_x Aug 01 '17 at 10:38
  • UI looks is design in such a way that we can't use input box. – Jyotish Singh Aug 01 '17 at 10:39
  • I would doubt that you can't style an input in a way that only a span could be styled. Also `contenteditable` will raise a huge chunk of problems in numerous browsers. But if you want to use it try listening for the `input` [event](https://developer.mozilla.org/en-US/docs/Web/Events/input). Also be aware that IE doesn't know about it. – cyr_x Aug 01 '17 at 10:42
  • for angular2 contenteditable, this might be what you need https://stackoverflow.com/questions/39023701/angular-2-contenteditable – Val Aug 01 '17 at 10:43
  • @cyrix, there's nothing wrong with using `contenteditable` elements. Form element `input` is not a replacement for them – Max Koretskyi Aug 01 '17 at 10:45

1 Answers1

4

For contenteditable you need to use input event. Here is what the docs say:

The DOM input event is fired synchronously when the value of an , , or element is changed... Additionally, it fires on contenteditable editors when its contents are changed. In this case, the event target is the editing host element...

input however is triggered on each change, while change is triggered on focusout, so you need to combine those.

class Component {
  tmp = ''l

  updateTmpData(e) {
    this.tmp = e.target.textContent;
  }

  updateData() {
     // use this.tmp
  }
}

... 
<span id="fname" (input)="updateTmpData(e)" (focusout)="updateData()"></span>
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488