PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, June 29, 2022

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

 June 29, 2022     angular, backend, comments, function, typescript     No comments   

Issue

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


Answered By - Zerotwelve
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing