Browse Source

ngIf 跟 else 實作

master
HarveyChou 2 years ago
parent
commit
a76881a140
  1. 15
      src/app/app.component.html
  2. 35
      src/app/app.component.spec.ts
  3. 27
      src/app/app.component.ts

15
src/app/app.component.html

@ -1,5 +1,10 @@
<button type="button" (click)="onReset()">重設工作事項</button>
<app-task
*ngFor="let task of tasks; trackBy: trackByItems"
[task]="task"
></app-task>
<button type="button" (click)="onLoad()">載入資料</button>
<button type="button" (click)="onClear()">清除資料</button>
<div *ngIf="tasks.length >= 1; else empty">
<app-task *ngFor="let task of tasks; let odd = odd" [class.odd]="odd" [task]="task"></app-task>
</div>
<ng-template #empty>
<div class="data-empty">無待辦事項</div>
</ng-template>

35
src/app/app.component.spec.ts

@ -1,35 +0,0 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'Learn'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('Learn');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('Learn app is running!');
});
});

27
src/app/app.component.ts

@ -1,28 +1,29 @@
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
styleUrls: ['./app.component.css'],
})
export class AppComponent {
tasks: Task[] = [
export class AppComponent implements OnInit {
tasks!: Task[];
ngOnInit(): void {
this.onLoad();
}
onLoad(): void {
this.tasks = [
new Task({ TaskSn: '001', TaskName: '待辦事項 A', State: 'Finish' }),
new Task({ TaskSn: '002', TaskName: '待辦事項 B', State: 'Doing' }),
new Task({ TaskSn: '003', TaskName: '待辦事項 C', State: 'None' }),
new Task({ TaskSn: '004', TaskName: '待辦事項 D', State: 'None' }),
];
trackByItems(index:number, task:Task):string{
return task.TaskSn;
}
onReset():void{
this.tasks=[
new Task({ TaskSn: '001', TaskName: '待辦事項 A', State: 'Finish' }),
new Task({ TaskSn: '002', TaskName: '待辦事項 B', State: 'Doing' }),
new Task({ TaskSn: '004', TaskName: '待辦事項 C', State: 'None' }),
new Task({ TaskSn: '005', TaskName: '待辦事項 D', State: 'None' }),
];
onClear(): void {
this.tasks = [];
}
}
Loading…
Cancel
Save