我显示在主team.component.ts的另一个组件(team-announcements.component)...中创建的模板中的数据,我将选择器用于团队公告,并添加[announcement] =“公告”和ngFor =“让公告公告“加载数据。如果该数组未返回任何数据,即IE中没有公告,该如何显示诸如“无公告”之类的占位符?
这是我在team.component.html中加载公告的地方。数据通过API服务提供,并在“ team.component.ts”中检索,有关对象的HTML如下。
team.component.ts(获取公告功能):
getAnnouncements() {
this.teamsService.getTeamAnnouncements(this.team.slug)
.subscribe(announcements => this.announcements = announcements);
console.log("announcements", this.announcements);
}
team.component.html
<div class="team-announcement">
<div class="announcement-title">Message of the Day</div>
<app-team-announcements
[announcement]="announcement"
*ngFor="let announcement of announcements">
</app-team-announcements>
</div>
这是上面的“ app-team-announcements”在一个单独的文件“ team-announcement.component.html”中模板化并导出,然后在上面的代码中使用的方式...
team-announcements.component.ts
import { Component, EventEmitter, Input, Output, OnInit, OnDestroy } from '@angular/core';
import { Team, Announcement, User, UserService } from '../core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-team-announcements',
templateUrl: './team-announcement.component.html'
})
export class TeamAnnouncementComponent implements OnInit, OnDestroy {
constructor(
private userService: UserService
) {}
private subscription: Subscription;
@Input() announcement: Announcement;
@Output() deleteAnnouncement = new EventEmitter<boolean>();
canModify: boolean;
ngOnInit() {
// Load the current user's data
this.subscription = this.userService.currentUser.subscribe(
(userData: User) => {
this.canModify = (userData.username === this.announcement.author.username);
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
team-announcements.component.html
<div class="announcement-text">
{{announcement.body}}
</div>
我不确定如何或在哪里“检查”数组长度以显示占位符。有人可以帮忙吗?
答案 0 :(得分:3)
如果要隐藏它并显示其他内容,则可以使用else
中的*ngIf
属性:
<div class="team-announcement">
<div class="announcement-title">Message of the Day</div>
<ng-container *ngIf="announcements.length != 0; else emptyArray">
<app-team-announcements
[announcement]="announcement"
*ngFor="let announcement of announcements">
</app-team-announcements>
</ng-container>
</div>
<ng-template #emptyArray>No announcements...</ng-template>
当您希望具有*ngFor
的元素取决于条件(*ngIf
)时,一个很好的选择是将带有*ngFor
的元素嵌套在<ng-container>
中, *ngIf
。 <ng-container>
的优点是它实际上不会成为DOM的一部分,但会服从*ngIf
。
答案 1 :(得分:0)
您可以插入一个仅在数组为空时显示的分区:
<div class="team-announcement">
<div class="announcement-title">Message of the Day</div>
<app-team-announcements
[announcement]="announcement"
*ngFor="let announcement of announcements">
</app-team-announcements>
<div *ngIf="announcements.length===0"> No announcements </div>
</div>
编辑:更正了错误