Angular 2如何在组件之间共享变量

时间:2017-04-22 19:00:12

标签: javascript angular typescript

我正在试图弄清楚如何在一组子组件中切换变量 我有一个可编辑的表单控件的组件,它可以在视图状态之间切换

import {
    Component,
    Input,
    ElementRef,
    ViewChild,
    Renderer,
    forwardRef,
    OnInit
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const INLINE_EDIT_CONTROL_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => InlineEditComponent),
    multi: true
};

@Component({
  selector: 'inline-edit',
  templateUrl: 'inline-edit.html',
  providers: [INLINE_EDIT_CONTROL_VALUE_ACCESSOR],
})
export class InlineEditComponent implements ControlValueAccessor, OnInit {

    @ViewChild('inlineEditControl') inlineEditControl: ElementRef;
    @Input() label: string = '';
    @Input() type: string = 'text';
    @Input() required: boolean = false;
    @Input() disabled: boolean = false;
    private _value: string = '';
    private preValue: string = '';
    public editing: boolean = false;
    public onChange: any = Function.prototype;
    public onTouched: any = Function.prototype;

    get value(): any {
        return this._value;
    }

    set value(v: any) {
        if (v !== this._value) {
            this._value = v;
            this.onChange(v);
        }
    }

    writeValue(value: any) {
        this._value = value;
    }

    public registerOnChange(fn: (_: any) => {}): void {
        this.onChange = fn;
    }

    public registerOnTouched(fn: () => {}): void {
        this.onTouched = fn;
    }

    constructor(element: ElementRef, private _renderer: Renderer) {
    }

    ngOnInit() {
    }

}


<div>
  <div [hidden]="!editing">
    <input #inlineEditControl [required]="required" [name]="value" [(ngModel)]="value" [type]="type" [placeholder]="label" />
  </div>
  <div [hidden]="editing">
    <label class="block bold">{{label}}</label>
    <div tabindex="0" class="inline-edit">{{value}}&nbsp;</div>
  </div>
</div>

我正在尝试创建一个简单的指令来使用这些组件并将编辑标志更改为true

export class EditForm {
   //I want to do something like this:
   public toggleEdit(fn: () => {}): void {
      var editableFormControls = $('#selector: 'inline-edit');
      editableFormControls.forEach(control => control.editing = true)
   }     
}

我想获取所有可编辑的表单控件并将所有这些控件中的编辑标志设置为true,我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可能需要实现一个服务来保持状态,并且所有子组件都订阅状态,并且父推送更改在那里。

import {Component, NgModule, VERSION, Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

export class EditableService {
  subject = new BehaviorSubject(true);
  getAsObservable() {
    return this.subject.asObservable();
  }
}

@Component({
  selector:'editable',
  template: '<div>i am editable {{ x | async}}</div>'
})
export class Editable {
  constructor(private editableService: EditableService) {
    this.x = editableService.getAsObservable();
  }
}

@Component({
  selector: 'my-app',
  template: `
    <editable></editable>
    <editable></editable>

    <hr/>
    <button (click)="change()">change</button>
  `,
  providers: [EditableService]
})
export class App {
   change() {
    this.editableService.subject.next(false);
   }

   constructor(private editableService: EditableService) {
    this.name = `Angular! v${VERSION.full}`;
  }

 }