Angular2模板:安全导航操作符和* ngIf

时间:2017-01-05 13:02:00

标签: templates angular asynchronous angular2-template

我的目标是在没有可用项目时隐藏元素。到目前为止我的模板:

<div *ngIf="(projects | async)?.userProjects.length !== 0">
    <div class="sortWrapper">
        <h3>Your projects</h3>
    </div>

    <div class="listElementWrapper">
        <div class="listElement" *ngFor="let userProject of (projects| async)?.userProjects" (click)="redirectToProject(project)">
            <h4>{{ userProject.ProjectName }}</h4>
        </div>
    </div>
</div>

使用安全导航操作符的* ngFor按预期工作。但第一行(* ngIf)并不存在。由于userProjects属性是异步的,因此长度不会以某种方式更新。我在这里错过了一个关键概念吗?

组件:private projects: Observable<any[]>;

2 个答案:

答案 0 :(得分:0)

?之前添加length

<div *ngIf="(projects | async)?.userProjects?.length == 0">

答案 1 :(得分:0)

我相信你希望它是!== 0。然后它会实际显示它何时有结果:)

<div *ngIf="(projects | async)?.userProjects.length !== 0">

<击>

显然这是一个有角度的问题。点击此处了解更多信息:

https://github.com/angular/angular/issues/9641

解决方案可能是不使用异步管道并在组件中设置变量userProjects

  

未经测试的代码

<div *ngIf="userProjects.length > 0">
    <div class="sortWrapper">
        <h3>Your projects</h3>
    </div>

    <div class="listElementWrapper">
        <div class="listElement" *ngFor="let userProject of userProjects" (click)="redirectToProject(project)">
            <h4>{{ userProject.ProjectName }}</h4>
        </div>
    </div>
</div>

这个组件是这样的:

export class UserProjectsComponent {

   public userProjects: UserProject[] = [];

   public projectSub: Subscription;

   constructor(public projectService: ProjectService){}

   ngOnInit() {
      this.projectSub = this.projectService.getUserProjects().subscribe((userProjects) => {
          this.userProjects = userProjects
      });
   }

   ngOnDestroy() {
      this.projectSub.unsubscribe();
   }
}

您也可以在projectService上定义userProject:

@Injectable()
export class ProjectService {

  public get userProjects(): UserProject[] {
     return this._userProjects;
  }  

  private _userProjects: UserProject[] = [];

  constructor(private http: Http){}

  public getUserProjects(): void {
     this.http.get().map(resp => resp.json()).subscribe((userProjects) => {
          this._userProjects = userProjects;
     });
  }
}

然后你可以按照我在上面的定义保留模板,但是将组件更改为更简单:

export class UserProjectsComponent {

   public get userProjects(): UserProject[] {
      return this.projectService.userProjects;
   }

   constructor(public projectService: ProjectService){}

   ngOnInit() {
      this.projectService.getUserProjects();
   }
}