所以說那個醬汁呢?
前面已經做好了股票資訊的呈現,但只有五支,如果要動態新增或刪除自己目前關注的股票,很顯然既有的功能是達不到的
這篇要透過 Angular Forms 以互動的方式增減關注的股票
Form 就 Form,為何是 Angular Forms?自然是因為 Angular 內建有支援很多方便的功能像是 validation, two-way binding, one-way binding, ...等等,日後會再詳談
既然是管理關注股票,跟顯示用的 Dashboard 沒什麼關係,建一個新的 Component 來處理吧!
ng generate component components/manage
再來又要對 AppComponent 的 html 作手腳了
<main class="mdl-layout__content" style="padding: 20px;">
<manage></manage>
</main>
接著,因為要用到 Angular Forms,我們要在 app.module.ts 加上下以的 import:
import { FormsModule } from '@angular/forms';
//...(略)
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
],
再來就是要把 ManageComponent 的邏輯填上了:
import { Component, OnInit } from '@angular/core';
import { StocksService } from 'src/app/services/stocks.service';
@Component({
selector: 'manage',
templateUrl: './manage.component.html',
styleUrls: ['./manage.component.css']
})
export class ManageComponent implements OnInit {
symbols: Array<string>;
stock: string;
constructor(private stockService: StocksService) {
this.symbols = this.stockService.get();
}
add() {
this.symbols = this.stockService.add(this.stock.toUpperCase());
this.stock = '';
}
remove(symbol) {
this.symbols = this.stockService.remove(symbol);
}
ngOnInit(): void {
}
}
Controller 搞定,來設計 View!
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--4-col"></div>
<div class="mdl-cell mdl-cell--4-col">
<form style="margin-bottom: 5px" (submit)="add()">
<input
name="stock"
[(ngModel)]="stock"
class="mdl-textfield__input"
type="text"
placeholder="Add Stock"
/>
</form>
<table
class="mdl-data-table mdl-data-table--selectable mdl-shadow--2dp"
style="width: 100%"
>
<tbody>
<tr *ngFor="let symbol of symbols">
<td class="mdl-data-table__cell--non-numeric">{{ symbol }}</td>
<td style="padding-top: 6px">
<button class="mdl-button" (click)="remove(symbol)">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="mdl-cell mdl-cell--4-col"></div>
</div>
小結一下