ng如果隐藏整个父div

时间:2018-07-14 15:02:28

标签: angular

<h1>{{profile.name}}</h1>
    <!-- shows the posts when the user is not logged in -->
    <div class="post" *ngFor="let post of posts">
        <p>{{post.title}} - {{post.content}}</p>
    </div>

    <!-- Does not show the posts title or content -->
    <div class="post" *ngFor="let post of posts">
        <p>{{post.title}} - {{post.content}}</p>
        <div  *ngIf="owner(post)">
            <button (click)="edit(post)">Edit</button>
            <button  (click)="delete(post)">Delete</button>
        </div>
    </div>
<new-post-form *ngIf="auth.isLoggedIn() && auth.getUserDetails()._id === id" (postCreated)="addPost($event)"></new-post-form>

我试图弄清楚为什么第二个ngFor指令在用户未登录时不显示任何内容。posts数组已在组件中成功设置(第一个ngfor指令在用户未登录时成功运行)。第二个ngfor指令应该显示如果用户未登录或用户的ID与帖子的author属性不匹配,但隐藏所有内容而不只是两个按钮的情况,第一个显示的内容。

这是相关的组件代码-

profile: Profile;
  posts: Post[];
  id: string;

  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id');


    this.data.getProfile(this.id)
      .subscribe(profile => {
        this.profile = profile;
      });

    this.data.getPosts(this.id)
        .subscribe(posts => {
        this.posts = posts;
      });
  }

owner(post) : boolean {
    return post.author === this.auth.getUserDetails()._id;
  }

1 个答案:

答案 0 :(得分:0)

您的功能owner可能在用户未登录时不起作用。因为this.auth.getUserDetails()可能是undefinednull

尝试以此替换您的代码:

owner(post) : boolean {
  return this.auth.getUserDetails() && post.author === this.auth.getUserDetails()._id;
}