I have a loop on a component which represents a list of graph cards on my real app.

I have copied this component ( and loop it ) as the original

Hello Component

export class HelloComponent  {
   message:string;
   printedMessage:string
   @Input() elm:string;
  constructor(private data: DataService, private router : Router) { }

  ngOnInit() {
    this.message = this.data.messageSource.value;
    this.data.messageSource.subscribe(message => this.message = message)

  }

  updateService(){
    this.data.changeMessage(this.message);
    this.printedMessage=this.data.messageSource.value
  }

  navigateToSibling(){
    this.router.navigate(['/sibling']);
  }
}

app component

<div *ngFor="let elm of [1,2,3,4]">
<hello [elm]= "elm"></hello>
</div>

<h1>Copy </h1>
<div *ngFor="let elm of [1,2,3,4]">
<hello [elm]= "elm"></hello>
</div>

DataService component

export class DataService {

  messageSource = new BehaviorSubject<string>("default message");
  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

Expected behaviour

What I would is when change the input value on the component 1 for example , only the value on the input of the copied component 1 changes.

Actual behaviour

Actually when I change a value inside an input all the other inputs are changings.

Here's a stackblitz example

1 Answers

0
Manish On

Below is a solution that will solve you issue. This may not be a perfect solution but you need something similar.

hello.html

<h1>App component {{elm}}</h1>
<input type="text" [(ngModel)]="message">

<button (click)="updateService()" type="button">Save</button> {{printedMessage}}

Data Service

import {
  Injectable
} from '@angular/core';
import {
  BehaviorSubject
} from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  messageSource = new BehaviorSubject < any > ("default message");
  constructor() {}

  changeMessage(message: string, elem: any) {
    this.messageSource.next({
      message: message,
      elem: elem
    });
  }

}

HelloComponent

import {
  Component,
  Input
} from '@angular/core';
import {
  DataService
} from "./dataService";
import {
  Router
} from '@angular/router';
@Component({
  selector: 'hello',
  templateUrl: './hello.html',
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  message: string;
  printedMessage: string
  @Input() elm: string;
  constructor(private data: DataService, private router: Router) {}

  ngOnInit() {
    this.message = this.data.messageSource.value;
    this.data.messageSource.subscribe(message => this.message = message.elem === this.elm ? message.message : this.message);

  }

  updateService() {
    debugger
    this.data.changeMessage(this.message, this.elm);
    this.printedMessage = this.data.messageSource.value.message;
  }

  navigateToSibling() {
    this.router.navigate(['/sibling']);
  }
}

Have also updated the Stackblitz Demo. Hope this helps :)