I've been struggling to fix few problems with contenteditable
div in Angular. The issues are as follow:
contenteditable
but the same value ref name. The problem is that every time I've been trying to submit the content to database, only the first content is not returning an empty string, the rest of the items have just been returning empty strings over and over again. I'm not sure how to fix it after browsing the Internet indefinitely.In app.component.ts I've this:
@ViewChild("new_message_ref")newMessageRef?: ElementRef;
newMessage:any = ""
//This the method that should be sending message content to backend
//but only sending successfully the date
newMessage(user: any) {
var messages = this.angFireBD.list("users/" + user.$key + "/messages");
messages.update(this.userService.currentUserUid, {
//and this the content I've been sending to database
content: this.newMessageRef?.nativeElement.innerText,
sent: new Date().toLocaleDateString()
})
}
In app.compenent.html, I've this:
<li *ngFor="let user of allUsers">
<div
#new_message_ref
type="text"
contenteditable="true"
placeholder="Send a message to introduce yourself"
[textContent]="newMessage"
>
</div>
...
<span (click)="newMessage(user)">Send</span>
</li>
<!-- This is my 2nd issue -->
<div placeholder="{{myVar}}"></div>
THANK YOU!!!
use @ViewChildren, not ViewChild. ViewChild only gets the first of all, e.g. :
@ViewChildren('new_message_ref') messages:QueryList<ElementRef>
See that you can get the element ref in position "index" using
const element=this.messages.find((_,i)=>i==index)
console.log(element.nativeElement.innerText)
Or loop over all
this.messages.forEach(=>{
console.log(x.nativeElement.innerText)
})
See the docs about QueryList