如何对 Angular 中的数组中的每个项目使用 contenteditable

How to use contenteditable for each item from an array in Angular

我一直在努力解决 Angular 中 contenteditable div 的一些问题。问题如下:

  1. 数组列表中的每个项目都有自己的 contenteditable 但具有相同的值引用名称。问题是每次我试图将内容提交到数据库时,只有第一个内容没有返回空字符串,其余项目只是一遍又一遍地返回空字符串。无限期地浏览互联网后,我不确定如何修复它。

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>
  1. 最后一个问题是我无法在占位符内绑定变量,但我现在可以忍受,因为我更关心第一个问题:
<!-- This is my 2nd issue -->

 <div placeholder="{{myVar}}"></div>

谢谢你!!!

使用 @ViewChildren,而不是 ViewChild。 ViewChild 只得到第一个,例如:

@ViewChildren('new_message_ref') messages:QueryList<ElementRef>

看到您可以使用

获取位置“index”中的元素 ref
   const element=this.messages.find((_,i)=>i==index)
   console.log(element.nativeElement.innerText)

或者遍历所有

this.messages.forEach(=>{
 console.log(x.nativeElement.innerText)
})

查看有关 QueryList

的文档