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?
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?
Share Improve this question edited Dec 15, 2016 at 12:22 Bazinga 11.2k7 gold badges41 silver badges66 bronze badges asked Dec 15, 2016 at 10:50 Shilpa NagavaraShilpa Nagavara 1,1652 gold badges18 silver badges33 bronze badges4 Answers
Reset to default 3You 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>
I do this which seems to work.
<div contenteditable="true" (keydown.enter)="onEnter($event)" />
Then in typescript:
onEnter($event) {
$event.preventDefault();
this.sendMessage();
}
in your ponent :
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>
You can achieve this by temporarily change value of you model wall.title
(by adding space at the end and remove it after 0ms :P ) which force angular to refresh div DOM element:
So change 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 ponent code:
public finishEditTeamName(event)
{
event.target.blur();
let str = this.wall.title;
this.wall.title = str + ' ';
setTimeout( () => {
this.wall.title = str;
}, 0);
}