我在一个组件上有一个循环,它代表了我真正的应用程序上的一个图形卡列表。
我已经将这个组件(并循环它)复制为原始
Hello组件
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示例
发布于 2019-05-10 10:17:24
下面是解决问题的解决方案。这可能不是一个完美的解决方案,但您需要类似的东西。
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演示。希望这会有所帮助:)
https://stackoverflow.com/questions/56075168
复制相似问题