iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 14
0
Modern Web

Angular10 實作教學系列 第 14

NG10鐵人賽 - 14 - 資料傳遞處理 - @Input 傳入資料要改寫或做變化處理

基本使用說明可以參考我之前寫過相關的文章

@Input 基礎使用
https://ithelp.ithome.com.tw/articles/10206340
@Output 基礎使用
https://ithelp.ithome.com.tw/articles/10206603

成果

https://i.imgur.com/PLInrsm.gif

app.component.html

<div class="form-check">
    <input class="form-check-input" type="radio" name="food" id="app" value="apple" checked [(ngModel)]="food">
    <label class="form-check-label" for="app">
        蘋果
    </label>
</div>
<div class="form-check">
    <input class="form-check-input" type="radio" name="food" id="banana" value="banana" [(ngModel)]="food">
    <label class="form-check-label" for="banana">
        香蕉
    </label>
</div>
<div class="form-check">
    <input class="form-check-input" type="radio" name="food" id="orange" value="orange" [(ngModel)]="food">
    <label class="form-check-label" for="orange">
        橘子
    </label>
</div>
<app-menu [food]="food"></app-menu>

app.component.ts

food = ['飯', 'oreo', '蛋糕'];

menu.component.html (子類別)

<ng-container *ngFor="let food of foods">
    <p>{{food.name}} - {{food.price}}元</p>
</ng-container>

menu.component.ts (子類別)

import { Component, OnInit, Input, OnChanges, SimpleChanges, SimpleChange } from '@angular/core';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit, OnChanges {
    @Input() food; // 傳進來的參數
    foods = []; // 顯示用

    ngOnInit(): void {
    }

    // 原本是傳 陣列,後面 radio button 只有 string
    // previousValue: any - 上次的值 (第一次會是 undefined)
    // currentValue: any - 現在的值
    // firstChange: boolean - 是不是第一次
    ngOnChanges(changes: SimpleChanges): void {
        const current = (changes.food as SimpleChange).currentValue;
        const isArray = Array.isArray(current);
        const beArray = isArray ? current : [current];
        this.foods = beArray.map(f => {
            return {name: f, price: 20};
        });
    }
}

參考來源

angular 官網 - OnChanges
https://angular.io/api/core/OnChanges


上一篇
NG10鐵人賽 - 13 - 圖片(2) - 檔案接API
下一篇
NG10鐵人賽 - 15 - 資料傳遞處理 - 照順序給值
系列文
Angular10 實作教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言