//父組件html <ul> <app-li [value] = "value" (liClick) = "liClick($event)"> </ul> //子組件 app-li 的 component.ts import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core'; //... @Input current: string; // Input 用於變量傳遞 @Output appClick = new EventEmitter<string>(); // Output 用於函數傳遞 //子組件 app-li 的html <li (click) = "appClick.emit(li.innerText)" #li1>{{current | async}}</li>
//service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class HeroService { constructor(){} //狀態 public value1: number; public string1: number; //函數 setValue(value1): void { this.value1 = value; } setString(string1): void { this.string1 = string1; } } //component.ts string$: string; number$: number; constructor(private testService: TestService) { this.string$ = testService.string1; this.number$ = testService.number1; } //html <p>{{string$}}</p> <p>{{number$}}</p> <input (keyup) = "testService.setValue(input1.value)" #input1/> <input (keyup) = "testService.setString(input2.value)" #input2/>
三. ngrx 狀態管理html
//action.ts import { Action } from '@ngrx/store'; export enum ActionTypes { Increment = '[Counter Component] Increment', Decrement = '[Counter Component] Decrement', Reset = '[Counter Component] Reset', } export class Increment implements Action { readonly type = ActionTypes.Increment; } export class Decrement implements Action { readonly type = ActionTypes.Decrement; } export class Reset implements Action { readonly type = ActionTypes.Reset; } //reducer.ts 純函數 import { Action } from '@ngrx/store'; import { ActionTypes } from './hero.actions'; export const initialState = 0; export function counterReducer(state = initialState, action: Action) { switch (action.type) { case ActionTypes.Increment: return state + 1; case ActionTypes.Decrement: return state - 1; case ActionTypes.Reset: return 0; default: return state; } } //組件中的應用 //component.ts import { Store, select } from '@ngrx/store'; import { Observable , of , interval} from 'rxjs'; import { Increment, Decrement, Reset } from '../hero.ngrx/hero.actions'; count$: Observable<number>; constructor(private store: Store<{ count: number }>) { this.count$ = store.pipe(select('count')); } increment() { this.store.dispatch(new Increment()); } decrement() { this.store.dispatch(new Decrement()); } reset() { this.store.dispatch(new Reset()); } //組件中的html <button (click)="increment()">Increment</button> <div>Current Count: {{ count$ | async }}</div> <button (click)="decrement()">Decrement</button> <button (click)="reset()">Reset Counter</button>