LoginSignup
3
4

More than 3 years have passed since last update.

Can't bind to 'ngIf' since it isn't a known property of 'div' in production build

Last updated at Posted at 2019-05-17

Can't bind to 'ngIf' since it isn't a known property of 'div' in production build

このエラーでstack overflowでよくある回答が、CommonModuleがインポートされていないから、というもの。app.module.tsで以下のようにしなさい、と。

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

中略

@NgModule({
    imports: [CommonModule],
  ...
})


全然そんなことしなくても良く、原因は別にあったという備忘録。

前提

ケース:Firestoreからデータを取ってきて、その中のidがhogehogeならば、という条件文で*ngIfを使いたかった。

コードとしてはこんな感じ

html

<div *ngFor="let post of posts">
      <div *ngIf="post.id == 'hogehoge'">
            hogehoge表示  
      </div>
      <div *ngIf="post.id !== 'hogehoge'">
            hogehogeじゃない表示
      </div>
  </div>

ts

// Firestoreからデータを取ってくるところ
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Post } from '../../class/post';
    post: Post;
    posts: Post[];

  getPosts() {
    this.postsCollection.valueChanges().subscribe(data => {
     this.posts = data;
    });
  }

これだとエラーがでる。


解決方法

Firestoreからデータをとってくる構文ね。この一括でとってくる簡単な書き方だとダメみたい。

こうする。

import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { Post } from '../../class/post';
import { Observable } from 'rxjs';          // 追加
import { map } from "rxjs/operators";       // 追加

    post: Post;
    posts: Observable<Post[]>;          // 変更

getPosts() {
    this.posts = this.postsCollection.snapshotChanges().pipe
    (map(actions => {
      return actions.map(action => {
        const data = action.payload.doc.data() as Post;
        const id = action.payload.doc.id;
        const uid = action.payload.doc.data().uid;
        return { id,uid,  ...data };
        });
      }));
} 

要はObserbableを使えと。

<div *ngFor="let post of posts | async">

HTMLの方はこの場合*ngFor文で| asyncをつけるように。


以上。

3
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4