Search code examples
angulartypescriptfunctionbackendcomments

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


I'm working on a website (basically a twitter clone), and I want to add comments to posts. To do so, I have to pass the ID of the tweet and the comment itself to the backend. So far I have the following code:

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

This gets called in the HTML as follows:

 <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>

Lastly the form and the sending function:

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}`, {}); }

When I run these, I get an undefined ID, and can't figure out the problem.


Solution

  • you can do it like this: (click)="homepageservice.toggle(tweet)" and in your service:

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