如何将按钮的 ID 传递给 Angular 函数?

How can I pass a button's id to an Angular function?

我在网站上工作(基本上是 Twitter 的克隆),我想在帖子中添加评论。为此,我必须将推文的 ID 和评论本身传递给后端。到目前为止,我有以下代码:

toggle(event: Event): void {
    let elementId: string = (event.target as Element).tagName;
    console.log(elementId);
    this.commentModel.value.ID = elementID;
  }

这在 HTML 中调用如下:

 <form [formGroup]="homepageservice.commentModel"
                    class="container d-flex row rounded-pill p-2 justify-content-between align-items-center w-80 addCommentBox"
                    id="add-comment" (submit)="onSendComment()">
                    <textarea type="text" name="comment" class="rounded-pill col" id="comment-input"
                        formControlName="commentcontent" placeholder="Write comment here...."></textarea>
                    <button type="submit" name={{tweet.ID}} id="addComment" class="btn btn-green rounded-pill"
                        (onclick)="homepageservice.toggle($event)">
                        <i class="bi bi-send-fill"></i>
                    </button>
                </form>

最后是表单和发送功能:

commentModel = this.fb.group({
commentcontent: [''],
id: [''] }) 

sendComment() {
const commentText = this.commentModel.value.commentcontent;
const id = this.commentModel.value.ID;
return this.http.post(this.apiUrl + `/Tweets/newComment? 
comment=${commentText}&tweetID=${id}`, {}); }

当我运行这些时,我得到一个未定义的ID,无法弄清楚问题。

你可以这样做:(click)="homepageservice.toggle(tweet)" 并为您服务:

toggle(tweet: any) {
    console.log(tweet);
    this.commentModel.value.ID = tweet.ID;
}

你为什么不尝试像这样传递 ID 参数?

<button type="submit" name={{tweet.ID}} id="addComment" class="btn btn-green rounded-pill"
                        (onclick)="sendComment(tweet.ID, $event)">
                        <i class="bi bi-send-fill"></i>
                    </button>