如何将删除按钮与删除请求绑定?

时间:2017-03-26 22:52:32

标签: html angular

我有一个html文件,显示使用ng的GET请求中的元素,我在显示的每个元素旁边显示一个红色删除按钮,单击时我希望从mongo数据库中删除该元素(触发删除)。我在expressjs中设置了DELETE,但我想知道如何将按钮绑定到列表中的相应元素?它在浏览器中加载如下:

detalis - unique_id                        del_button
detalis - unique_id                        del_button
detalis - unique_id                        del_button

这是我的组件:

export class DetailsComponent implements OnInit {
   messages: Message[] = [];

    constructor(private messageService: MessageService) {}

    ngOnInit() {
        this.messageService.getMessages()
            .subscribe(
                messages => this.messages = messages,
                error => console.error(error)
            );
            console.log(this.messages);
    }

    onDeleteMessage() {
       this.messageService
      .deleteServiceWithId("Id", "8631")
      .subscribe(
          result => console.log(result),
          error => console.error(error)
        );
    }

}

用作模板的HTML:

<div class="bs-example">
    <div class="panel-group" [attr.id]="'accordion_' + i" *ngFor="let message of messages; let i = index;">
        <div class="panel panel-default" >
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" [attr.data-parent]="'#accordion_' + i" [attr.href]="'#collapseOne_' + i">{{ message.firstName }} {{ message.lastName }}</a>
                </h4>
            </div>
            <div [attr.id]="'collapseOne_' + i" class="panel-collapse collapse">
                <div class="panel-body">
                  details here {{ message.empId }} 
                    <span class="pull-right">
                        <button type="button" class="btn btn-danger" aria-label="Left Align" (click)="onDeleteMessage()">
                        <span class="glyphicon glyphicon-remove-sign pull-right" aria-hidden="true"></span>
                        </button>
                    </span>    
                </div>
            </div>
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

对于每个删除按钮,将要删除的消息的id传递给onDeleteMessage()。

<!-- I'm not sure what the name for each id is but I'm assuming 
     its empId from the template you provided -->
<button class="btn btn-danger"
        aria-label="Left Align"
        type="button"
        (click)="onDeleteMessage(message.id)">
</button>

然后你的组件功能

onDeleteMessage(id: Number) {
   this.messageService
       .deleteServiceWithId(id)
       .subscribe(
          result => console.log(result),
          error => console.error(error)
   );
}