删除项目后隐藏元素,如果请求成功,则删除它,Angular 4

时间:2017-08-05 21:08:14

标签: angular typescript

我正在使用Angular 4.3.3。我想知道如果用户点击删除链接我可以隐藏--plugin,如果请求成功,那么删除它,否则如果请求失败,那么再次显示元素。

这是删除的打字稿代码:

<div>

这是HTML:

import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';

...

    constructor(private http: HttpClient, private globals: Globals, private activatedRoute: ActivatedRoute) { }

    deleteComment(url, index) {
        this.http.delete(url).subscribe(
        res => {
            console.log('success');
        },
        err => {
            console.log('Error occured.');
        });
    }

3 个答案:

答案 0 :(得分:1)

发表评论&#34;显示&#34;字段(最初都设置为true)然后在单击删除链接时切换。如果元素被成功删除,则将元素拼接出数组并强制ngFor重新渲染。如果删除失败,请显示元素

// html
<!-- Use [hidden] directive to hide element if show === false -->
<div *ngFor="let comment of result?.comment" [hidden]="comment.show">
    <!-- Other HTML -->
</div>

// ts
deleteComment(url, index) {
    // hide element
    this.result.comments[index].show = false; 

    this.http.delete(url).subscribe(
    res => {
        console.log('success');
        // remove element from array
        this.result.comments.splice(index, 1); 
        // needed to copy array. this allows ngFor to detect that the array has changed, causing ngFor to re-render 
        this.result.comments = this.result.comments.slice(0); 
    },
    err => {
        console.log('Error occurred.');
        // show element if api failed
        this.result.comments[index].show = true;
    });
}

<强>更新

将ngIf指令的使用更改为[hidden]指令,因此该元素是隐藏的而不是未呈现的(根据Shane的评论)

答案 1 :(得分:0)

设置布尔属性 成功删除:可观察 成功为真/错误为假

使用* ngIf =&#34; sucessfullyDeleted |异步&#34;在你想要隐藏的区域

答案 2 :(得分:0)

解决了 LLai ,但有一些变化。

    deleteComment(url, index) {
    this.result['comments'][index].hidden = true;
    this.http.delete(url).subscribe(
        res => {
            console.log('success');
            this.result['comments'].splice(index, 1);
        },
        err => {
            console.log('Error occured.');
            this.result['comments'][index].hidden = false;
        }
    );
}

HTML代码

<div *ngFor="let comment of result?.comments; let i = index" [hidden]="comment.hidden">
<a (click)="deleteComment(comment?._links.delete.href, i)">remove {{comment?.id}}</a>

<div class="media-body">
    {{comment?.content}}
</div>