angular - [(NgModel)] 是否更新行为主题?
问题描述
考虑以下场景,也可在此处获得https://stackblitz.com/edit/ionic-4-observables-playground:
问题
当我修改输入字段时, 和 的值会u1
发生u3
变化。由于[(NgModel)]
与 纠缠不清u1
,因此我希望u1
并u3
在输入新值后立即在内存中进行修改,但对于u1
not只能瞬时读取u3
。
我错过了什么?
问题编辑 1
我期望:[(ngModel)]="u1.username"
因为双向数据绑定而改变它的值,但不是u3
因为没有任何 NgModel<p>u3: {{u3.username}}</p>
设想
主页.ts
import { Component } from '@angular/core';
import {Observable, BehaviorSubject} from 'rxjs';
import 'rxjs/add/observable/from';
import {UserService} from '../user.service'
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.css'],
})
export class HomePage {
private u ='1'
private all
private u1 = {username: undefined}
private u2 = {username: undefined}
private u3 = {username: undefined}
constructor(private users:UserService){}
ngOnInit(){
this.u3 = this.users.findByUsername(this.u)
this.users.userList.subscribe( (data) => {
this.all = data
this.u1 = this.users.findByUsername(this.u);
this.u2 = data[1]
});
}
}
用户服务.ts
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable, BehaviorSubject} from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
public userList : BehaviorSubject<any[]> = new BehaviorSubject([
{ username: '1'}, {username: '2'}]);
constructor() {}
findByUsername(username: string) {
return this.userList.value.find(each => each.username === username);
}
}
主页.html
<ion-content padding>
<ion-item>
<ion-label position="floating">username</ion-label>
<ion-input
name="username"
type="text"
[(ngModel)]="u1.username"
required
></ion-input>
</ion-item>
<p *ngFor="let each of all; let i = index">u{{i +1}}: {{each.username}}</p>
<p>u3: {{u3.username}}</p>
</ion-content>
解决方案
u1
并且u3
是对同一个对象的两个引用。所以如果你修改u1
,你也会修改u3
:它们是同一个对象:
this.u3 = this.users.findByUsername(this.u)
// so u3 is the element from the list which has this.u as its name
this.u1 = this.users.findByUsername(this.u);
// so u1 is also the element from the list which has this.u as its name
推荐阅读
- reactjs - React Material-Table 如何传递 rowData 参数?
- javascript - 麦克风访问 Microsoft Edge
- arangodb - 如何在 ArangoDB 中的对象数组中过滤和排序对象数组
- c# - 如何在 ListView.SelectionChanged 上获取 SelectedItem 的父项
- c++ - 将 doxygen 转换为乳胶到 pdf 的问题
- android - 如何将 Azure DevOps 管道上的 .properties 文件设置为某种环境变量?
- sql - 如何返回嵌套的 JSON 数组
- angular - 在星云寄存器组件中添加自定义字段
- sas - SAS中的朴素贝叶斯分类器
- javascript - 使用 Highcharts 映射 json 数据的问题