Angular 4 NgModel不绑定数据

时间:2017-07-01 21:44:44

标签: angular firebase angular-ngmodel angularfire2

NgModel没有处理此组件。我已经导入了FormsModule和东西。其他功能如* ngIf和angled * ngFor在其他组件上运行良好。查看app.module。

帮助!

我正在使用firebase和angularfire2。

我的组件:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { CommonModule } from '@angular/common';

import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import * as firebase from 'firebase/app';

import { Rating } from '../rating';

import 'rxjs/add/operator/SwitchMap';

@Component({
    selector: 'app-view-rating',
    templateUrl: './view-rating.component.html',
    styleUrls: ['./view-rating.component.css']
})

export class ViewRatingComponent implements OnInit {

    name: any;
    rating: FirebaseObjectObservable<any>;
    user: firebase.User;
    item: any;

    constructor(
        private route: ActivatedRoute,
        private afAut: AngularFireAuth,
        private afDb: AngularFireDatabase) {
            this.afAut.authState.subscribe((auth) => {
                this.user = auth;
            })
        }

    ngOnInit(): void {
        this.name = this.route.snapshot.paramMap.get('item');
        this.rating = this.afDb.object(this.user.uid + '/' + this.name);
        console.log(this.rating)
    }
}

HTML:

<div class="form-container">

    <div *ngIf="rating" >
        <input [(ngModel)]="rating.name" name="name" >
    </div>
    
</div>

1 个答案:

答案 0 :(得分:0)

rating的类型为observable,您如何将其用于ngModel。您需要订阅它并分配给其他对象并将该对象用作ngModel

声明一个类型为any且不可观察的对象,如下所示

ratingObject:any;

this.rating = this.afDb.object(this.user.uid + '/' + this.name);
this.rating.subscribe(data =>{
        this.ratingObject = data;
});

然后在HTML中使用,如下所示,

<div *ngIf="ratingObject" >
    <input [(ngModel)]="ratingObject.name" name="name" >
</div>