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 the enter button after editing the contents of the div, I want to blur the div. A new line symbol is currently being added and a new line is displayed in the user interface.

How do I achieve this?

+5
source share
4 answers

You need to prevent the default operation: (which in this case should add a 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> 
+3
source

in your component:

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

in the 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> 
+1
source

You can achieve this by temporarily changing the value of your wall.title model (adding space to the end and deleting it after 0ms: P), which forces angular to update the DOM div element:

So, change the template to this:

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

And in the component code:

 public finishEditTeamName(event) { event.target.blur(); let str = this.wall.title; this.wall.title = str + ' '; setTimeout( () => { this.wall.title = str; }, 0); } 
0
source

I do it, it seems to work.

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

Then in typescript:

  onEnter($event) { $event.preventDefault(); this.sendMessage(); } 
0
source

Source: https://habr.com/ru/post/1261323/


All Articles