代码之家  ›  专栏  ›  技术社区  ›  hous

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

  •  0
  • hous  · 技术社区  · 8 年前

    <div>

    这是删除的typescript代码:

    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.');
            });
        }
    

    这是HTML:

    <div *ngFor="let comment of result?.comments; let i = index">
        <a (click)="deleteComment(comment?._links.delete.href, i)">remove {{comment?.id}}</a>
    
        <div class="media-body">
            <small>{{comment?.createdAt|date:'shortDate'}}</small>
            <p>{{comment?.content}}</p>
        </div>  
    </div>
    
    3 回复  |  直到 8 年前
        1
  •  1
  •   LLai    8 年前

    给评论一个“显示”字段(最初全部设置为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指令的使用更改为[隐藏]指令,因此元素是隐藏的,而不是未渲染的(根据Shane的评论)

        2
  •  0
  •   JGFMK    8 年前

    成功删除:可见 成功时为true/错误时为false

    在要隐藏的区域中使用*ngIf=“SuccessFullyDeleted | async”

        3
  •  0
  •   hous    8 年前

    由于以下原因解决 但有一些变化。

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

    Th 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>
    

    推荐文章