Browse Source

響應式表單

利用FormControl建立單一欄位表單,並用console紀錄
master
HarveyChou 2 years ago
parent
commit
df83d27fb6
  1. 3
      src/app/app.component.html
  2. 18
      src/app/app.component.ts
  3. 4
      src/app/app.module.ts
  4. 28
      src/app/task.service.ts
  5. 4
      src/app/task.ts

3
src/app/app.component.html

@ -1 +1,2 @@
<pre>{{ tasks | json }}</pre>
查詢條件:<input type="text" [formControl]="condition" />
<button type="button" (click)="onSearch()">查詢</button>

18
src/app/app.component.ts

@ -1,22 +1,16 @@
import { HttpResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Task } from './task';
import { TaskService } from './task.service';
@Component({ @Component({
selector: 'my-app', selector: 'my-app',
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.css'], styleUrls: ['./app.component.css'],
}) })
export class AppComponent implements OnInit {
tasks: Task[] = [];
export class AppComponent {
readonly condition = new FormControl();
constructor(private taskService: TaskService) {}
ngOnInit(): void {
this.taskService.getList().subscribe((res: HttpResponse<any>) => {
this.tasks = res.body;
});
onSearch(): void{
console.log(`查詢條件:${this.condition.value}`);
} }
} }

4
src/app/app.module.ts

@ -1,11 +1,11 @@
import { NgModule } from '@angular/core'; import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser'; import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component'; import { AppComponent } from './app.component';
@NgModule({ @NgModule({
imports: [ BrowserModule, FormsModule ],
imports: [ BrowserModule, ReactiveFormsModule ],
declarations: [ AppComponent ], declarations: [ AppComponent ],
bootstrap: [ AppComponent ] bootstrap: [ AppComponent ]
}) })

28
src/app/task.service.ts

@ -1,28 +0,0 @@
import { HttpResponse } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { HttpEventType } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { Task } from './task';
@Injectable({
providedIn: 'root',
})
export class TaskService {
constructor(private httpClient: HttpClient) {}
getList(): Observable<HttpEvent<Task[]>> {
return this.httpClient
.get<Task[]>('assets/tasks.json', {
observe: 'events',
reportProgress: true,
})
.pipe(
tap((event) =>
console.log(`Http Event Type = ${HttpEventType[event.type]}`)
)
);
}
}

4
src/app/task.ts

@ -1,4 +0,0 @@
export class Task {
subject!: string;
content!: string;
}
Loading…
Cancel
Save