[英]RxJS behavior subject and Angular ngModel binding with ngFor
不知道如何問這個,所以如果有人可以解決它,請這樣做。 如果我在頁面上兩次放置一個角度分量並從行為主題獲取數據,則一切工作正常,直到我使用ngModel綁定到輸入。 好像我不明白發生了什么。 我已經裝了一個小矮人。 更新輸入時,它隨處更新。 我不確定自己是否很清楚,但希望這個笨拙的人能使它變得顯而易見。
http://plnkr.co/edit/OQFEGVJAJF5kHhWoTOpm?p=preview
應用程序組件:
import { Component } from '@angular/core';
import { FormsModule, FormBuilder, Validators } from '@angular/common';
import { TodoComponent } from 'app/todo.component';
import { TodoService } from 'app/todo.service';
@Component({
selector: 'todo-app',
template: `
<h3>Component 1</h3>
<todo-component></todo-component>
<br /><br />
<h3>Component 2</h3>
<todo-component></todo-component>
`
})
export class AppComponent {
constructor() { }
}
組件:
import { Component } from '@angular/core';
import { TodoService } from 'app/todo.service';
@Component({
selector: 'todo-component',
template: `
<div *ngFor="let t of test | async">
<div>test: {{t.prop}}</div>
<div>test: <input [(ngModel)]="t.prop"></div>
</div>
`
})
export class TodoComponent {
private test: any;
constructor(private todoService: TodoService) { }
ngOnInit() {
this.test = this.todoService.test;
}
}
服務
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class TodoService {
private initialTestState = [{prop: 'val'}];
private test$: BehaviorSubject<[]>;
private test: Observable<[]>;
constructor() {
this.test$ = new BehaviorSubject<[]>(this.initialTestState);
}
get test() {
return this.test$.asObservable();
}
}
您應該返回不同的對象引用
get test() {
let obj = [{prop: 'val'}];
return new BehaviorSubject<[]>(obj);
}
訂閱服務並為不同的對象使用index
@Component({
selector: 'todo-component',
template: `
<div *ngFor="let t of test; let i = index; ">
<div>test: {{test[i].prop}}</div>
<div>test: <input [(ngModel)]="test[i].prop"></div>
</div>
`
})
export class TodoComponent {
private test: any;
constructor(private todoService: TodoService) { }
ngOnInit() {
this.todoService.test.subscribe(o => this.test = o);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.