我想问一下如何在Angular 2中实现这个逻辑: 我有这样的帖子:
<div class="postDetail clearfix">
<div class="title float-left"><a href="#">Lorem ipsum dolor sit</a></div>
<div class="createdAt float-right">before 10 hours</div>
<br>
<div class="desc float-left">Lorem ipsum dolor sit amet, <b>consectetur</b> adipisicing.</div>
<div class="createdAt float-right">Preview >></div>
<br>
</div>
点击&#34;预览&gt;&gt;&#34;我想在最后一个br标签后显示这段代码:
<div class="loading">
<mat-spinner [diameter]="40" [strokeWidth]="5"></mat-spinner>
</div>
当异步服务器调用完成且我在redux中有数据时,我想显示以下代码而不是之前加载:
<div class="preview" style="display: none;">
<img src="...">
<span class="name">Name Surname</span>
<p>Lorem ipsum dolor ...</p>
<div class="foot">
<b>Responses:</b> 221 | <a href="#">Show all</a>
</div>
</div>
我不知道我应该使用什么逻辑。
它应该如何运作? 1.服务器调用onInit加载标题和元数据 2.单击预览按钮后,将显示加载微调器并使服务器调用有关特定帖子的数据(在初始调用时加载的数据太多) 3.当服务器调用successl时,用上面提供的实际数据替换加载
答案 0 :(得分:1)
您可以在不同的模板上使用* ngIf,并根据您的组件状态显示所需的模板。
示例:强>
编辑:* ngFor
示例模板
<div *ngFor="let user of users">
<div class="postDetail clearfix" *ngIf=" ! user.loading && ! user.loaded">
<div class="title float-left"><a href="#">Lorem ipsum dolor sit</a></div>
<div class="createdAt float-right">before 10 hours</div>
<br>
<div class="desc float-left">Lorem ipsum dolor sit amet, <b>consectetur</b> adipisicing.</div>
<div class="createdAt float-right" (click)="loadPreviewData(user)">Preview >></div>
<br>
</div>
<div class="loading" *ngIf="user.loading">
<mat-spinner [diameter]="40" [strokeWidth]="5"></mat-spinner>
</div>
<div class="preview" style="display: none;" *ngIf="user.loaded">
<img src="...">
<span class="name">Name Surname</span>
<p>Lorem ipsum dolor ...</p>
<div class="foot">
<b>Responses:</b> 221 | <a href="#">Show all</a>
</div>
</div>
</div>
组件
import { Component } from '@angular/core';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
public users: Array<any>;
constructor() {};
ngOnInit() {
// Get your initial value
this.users.forEach(user => {
user.loaded = false;
user.loading = false;
})
}
loadPreviewData(user) {
user.loading = true;
this.loadRemoteData().subscribe(data => {
user.loading = false;
user.loaded = true;
user.data = data;
// Display new data
})
}
loadRemoteData() {
// Method requesting data
}
};