Angular 2 - send textarea value to a shared compon

2020-02-13 05:49发布

问题:

I have a textarea in the first page and when i go to next page i need this value to show in a notepad component that is shared in the next pages but at the same time i need that when i write new info in the shared component first and new information can be saved and displayed. i need to use angular2 and i cant use any stuff from github.enter image description here

回答1:

Since its not a parent-child relation, you can use shared service and pass the textarea value using setter and getter.

Example:

form.component.ts:

@Component({
  selector: 'form1-component',
  template: `
    <h3>Form 1</h3>
        <textarea [(ngModel)]="input"></textarea>
        <button (click)="save(input)">Save</button>
  `,
})
export class Form1 {
  input: any;

  constructor(private appState: AppState){

  }

  save(val){
    this.appState.setData(val);
  }
}

shared.service.ts:

@Injectable()
export class AppState {
  public formData;

  setData(value){
    this.formData = value;
  }

  getData(){
    return this.formData;
  }
}

other.component.ts:

@Component({
  selector: 'summary',
  template: `
    <h3>Summary From Form 1</h3>
    <div>{{data}}</div>
  `,
})
export class Summary {
  data: any;

  constructor(private appState: AppState){
    this.data = this.appState.getData();
  }
}

Plunker demo



回答2:

You can use @Input decorator if there is parent child relationship between components. Else make use of Services or BehaviourSubject. These are the following approaches based on priority:

  1. Using Services(Most Recommended).
  2. Using Behavior Subjects from RxJS library.
  3. Use Redux for state management.
  4. Using browser storage(session/local) but least recommended as prone to data security.


回答3:

Use cookies with ReactiveFormsModules, only saving to cookies when you have valid data.

npm install cookies-js --save

app-module.ts

...
imports: [ReactiveFormsModule]
...

MyComponent.html

...
<form [formGroup]="form">
  <input name="a" formControlName="b">
</form>
...

MyComponent.ts

import {Component, OnInit} from '@angular/core';
import {FormGroup,FormBuilder,Validators} from '@angular/forms';
import * as Cookies from 'cookies-js';

export class MyComponent implements OnInit{

  private static readonly COOKIE_DATA = 'data_to_save';

  form : FormGroup;

  constructor(private fb: FormBuilder) {

     this.form.fb.group({
     b: ['' Validators.required] 
     });
  }
  ngOnInit() {
    const data = Cookies.get(MyComponent.COOKIE_DATA);
    if (data) {
      this.form.setValue(JSON.parse(data));
    }
    this.form.valueChanges
     .filter(() => this.form.valid)
     .do(validData => Cookies.set(COOKIE_DATA, JSON.stringify(validData)
     .subscribe()
  }
}