Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: blur contenteditable div on enter

I have a contenteditable div that looks like this:

 <div class="wall-title col-sm-12" 
        [attr.contenteditable]="wall.title && wall.title !== 'Favorites'" 
        (blur)="wallNameChanged($event.target.outerText)"
        (keyup.enter)="wallNameChanged($event.target.outerText)">
           {{wall.title}}
 </div>

When the user presses enter after editing the div content, I want to blur the div. Currently, a new line character is getting added and a new line is visible in the UI.

How do I achieve this?

like image 749
Shilpa Nagavara Avatar asked Dec 15 '16 10:12

Shilpa Nagavara


3 Answers

You need to prevent the default operation: ( which in this case is to add new line )

wallNameChanged($event) {
  $event.preventDefault();
  $event.target.blur();
  // remove extra lines
  let text = $event.target.outerText.replace(/(\r\n|\n|\r)/gm,"");
  // do whatever you need with the text
}

<div (keyup.enter)="wallNameChanged($event)">
   {{wall.title}}
</div>
like image 55
Bazinga Avatar answered Sep 20 '22 23:09

Bazinga


I do this which seems to work.

<div contenteditable="true" (keydown.enter)="onEnter($event)" />

Then in typescript:

  onEnter($event) {
    $event.preventDefault();
    this.sendMessage();
  }
like image 45
jrock10 Avatar answered Sep 20 '22 23:09

jrock10


in your component :

onEnter($event){
  $event.target.blur()
  $event.preventDefault()
  this.wallNameChanged($event.target.outerText)
}

in your template :

<div class="wall-title col-sm-12" 
             [attr.contenteditable]="wall.title && wall.title !== 'Favorites'" 
             (blur)="wallNameChanged($event.target.outerText)"
             (keyup.enter)="onEnter($event)">
            {{wall.title}}
</div>
like image 44
n00dl3 Avatar answered Sep 20 '22 23:09

n00dl3