ng2 父子组件传值 - 状态管理

一. 父子组件之间进行直接通话

//父组件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 状态管理

//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>
posted on 2019-05-31 18:40  长安城下翩翩少年  阅读(357)  评论(0编辑  收藏  举报