'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 1:[1]
Why don't you try pass an ID parameter like this?
<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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hoà ng Gia Thiên |
