Angular 2 和 Angularfire2 中的三向绑定 [英] Three way binding in Angular 2 and Angularfire2
问题描述
我正在尝试使用 AngularFire 2 (2.0.0-beta.2) 将输入元素三向绑定到 Angular.js 2 (2.0.0-rc.4) 中的 firebase 数据库.
I am trying to three-way bind an input element to firebase database in Angular.js 2 (2.0.0-rc.4), using AngularFire 2 (2.0.0-beta.2).
我有一个非常简单的 html,例如:
I have a very simple html like:
<form (ngSubmit)="onSubmit()" #commentForm="ngForm">
<input [(ngModel)]="model.author" type="input" name="author" required>
</form>
在我的组件中,为了将这个输入的内容保存和检索到 firebase,我有一个这样的实现:
In my component, to save and retrieve contents of this input to firebase, I have an implementation like this:
export class CommentFormComponent implements OnInit, AfterViewInit {
@ViewChild("commentForm") form;
// http://stackoverflow.com/questions/34615425/how-to-watch-for-form-changes-in-angular-2
firebaseInitComplete = false;
model: Comment = new Comment("", "");
firebaseForm: FirebaseObjectObservable<Comment>;
constructor(private af: AngularFire) { }
ngAfterViewInit() {
this.form.control.valueChanges
.subscribe(values => {
// If we haven't get the initial value from firebase yet,
// values will be empty strings. And we don't want to overwrite
// real firebase value with empty string on page load
if (!this.firebaseInitComplete) { return; }
// If this is a change after page load (getting initial firebase value) update it on firebase to enable 3-way binding
this.firebaseForm.update(values);
});
}
ngOnInit() {
this.firebaseForm = this.af.database.object("/currentComment");
// Listen to changes on server
this.firebaseForm.subscribe(data => {
this.firebaseInitComplete = true; // Mark first data retrieved from server
this.model = data;
});
}
}
上面的代码有效,当用户实时输入内容时,我能够读取初始 firebase 值并更新 firebase 上的值.
The code above works, I am able to read initial firebase value and update value on firebase when user type something in real time.
但是有一个手动逻辑来检查 this.firebaseInitComplete
并添加 ngAfterViewInit
来监听更改感觉有点错误,我只是为了让它工作.
But having a manual logic to check for this.firebaseInitComplete
and adding ngAfterViewInit
to listen for changes feels a little bit wrong and I am just hacking it to work.
是否有更好的三向绑定实现,并且组件内部的逻辑更少?
Is there a better implementation of three-way binding with less logic inside component?
推荐答案
七个月后,我有一个答案给你.. 扩展 ngModel 语法..
Seven months later and I have an answer for you.. extended ngModel syntax..
<input [ngModel]='(model|async)?.author' (ngModelChange)="model.update({author: $event})">
[] 块是一个 getter,而 () 块是一个 setter.由于模型的 getter 实际上是在解包 FirebaseObjectObservable,因此您必须使用 FirebaseObjectObservable 的绑定来设置它.
The [] block is a getter and the () block is a setter. Since the model's getter is actually unwrapping the FirebaseObjectObservable, you have to use the FirebaseObjectObservable's binding to set it.
这篇关于Angular 2 和 Angularfire2 中的三向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!