Home > Software design >  How can I pass a button's id to an Angular function?
How can I pass a button's id to an Angular function?

Time:05-23

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"
                    
                    id="add-comment" (submit)="onSendComment()">
                    <textarea type="text" name="comment"  id="comment-input"
                        formControlName="commentcontent" placeholder="Write comment here...."></textarea>
                    <button type="submit" name={{tweet.ID}} id="addComment" 
                        (onclick)="homepageservice.toggle($event)">
                        <i ></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.

CodePudding user response:

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

CodePudding user response:

Why don't you try pass an ID parameter like this?

<button type="submit" name={{tweet.ID}} id="addComment" 
                        (onclick)="sendComment(tweet.ID, $event)">
                        <i ></i>
                    </button>
  • Related