简体   繁体   中英

Angular 2 How to share variables between components

I'm trying to figure out how to switch a variable in a group of child components I have this component for a editable form control which switches between view states

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>

I'm trying to create a simple directive to consume these components and change the editing flag to 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)
   }     
}

I want to grab all of the ediiitable form controls and set the editing flag in all of them to true, how can I do this?

You might need to implement a service that keeps the state and all child component subscribe to the state and parent push changes there.

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}`;
  }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM