单击Angular中的原始对象时触发克隆的组件

时间:2019-05-10 09:57:07

标签: javascript angular observable

我在一个组件上有一个循环,该循环代表了我的真实应用程序中的图形卡列表。

我已将此组件复制(并循环播放)作为原始文件

您好组件

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组件

export class DataService {

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

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

}

预期行为

例如,当更改组件1的输入值时,我将是什么,只有复制的组件1的输入上的值会更改。

实际行为

实际上,当我更改输入中的值时,所有其他输入都在更改。

这里是stackblitz example

1 个答案:

答案 0 :(得分:0)

以下是可以解决您问题的解决方案。这可能不是一个完美的解决方案,但是您需要类似的东西。

hello.html

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

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

数据服务

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']);
  }
}

还更新了Stackblitz Demo。希望这会有所帮助:)