我正在学习Angular 6,只是想将一些我学到的东西放到togheter上,我目前遇到了一个我找不到答案的问题。我正在尝试使用* ngFor更改LI的样式,具体取决于索引是First,Last,Odd还是Even。到目前为止,一切正常,但是我不知道如何为“ Last”做这件事,因为我将所有新对象添加到列表中时,它显然是最后一个,因此它呈现了最后一个颜色。
我知道该怎么做,但真正的问题是我正在从表单中动态地将内容添加到列表中,但我不确定如何评估“ Last”以使其他颜色变为正确的颜色。
请记住,我仍然是个新手,看起来可能很凌乱,而且我也了解,自HTMl5以来,我正在进行的某些客户端验证可能不是最佳的或不需要的,但我还是要学习它。
这是我的组件HTML代码
>
<h1>List of courses :</h1><br>
<div *ngIf="courses.length > 0; then coursesList else noCourses"></div>
<ng-template #coursesList>
<h2>List of Courses :</h2>
<ul *ngFor="let course of courses; index as i;">
<li [ngStyle]="{'background-color':getColor(i)}" style="color: white;">
<strong>Index : </strong>{{i}} <strong>ID : </strong>{{course.id}} <strong>Name</strong> : {{course.name}}
<button (click)="onRemove(i)">Remove</button>
<button (click)="onModify(i)">Modify</button>
</li>
</ul>
</ng-template>
<ng-template #noCourses>
<h5>There are no courses in this list. Use the form bellow to add some.</h5>
</ng-template>
<div (keyup.enter)="onAdd()">
<span>ID : <input type="number" (keypress)="checkNumber($event)" [(ngModel)]="fields.id" …Run Code Online (Sandbox Code Playgroud) 出于学习目的,我试图从json虚假API中获取数据,并在返回Observable之前为所有标题添加“嘿”。到目前为止,如果我不使用Map,即使在使用map时,我也可以显示数据;如果我console.log我的变量,它显示为Observable,但它不会显示在模板中。
<div class="col-6" *ngIf="courseDatas$ | async as courses else NoData">
<div class="card" *ngFor="let course of courses">
<div class="card-body">
<span><strong>User ID is : </strong>{{course.userId}}</span><br>
<span><strong>Title is : </strong>{{course.title}}</span><br>
<span><strong>Body is : </strong>{{course.body}}</span><br>
<span><strong>ID is : </strong>{{course.id}}</span>
</div>
<ng-template #NoData>No Data Available</ng-template>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
应用程序组件:
import {Component, OnInit} from '@angular/core';
import {PostsService} from "./posts.service";
import {Observable} from "rxjs";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
courseDatas$ : Observable<any>;
constructor(private posts : PostsService){}
ngOnInit(){
this.courseDatas$ = …Run Code Online (Sandbox Code Playgroud)