I've just started learning Angular4 and I am facing an issue I cannot explain.
I'm now trying to build two components :
My main component is chatComponent it is supposed to display a list of child components msgComponent.
For this I defined an array of message msgArray in app.chatComponent and iterate over the messages through à *ngFor directive. For each messages I want to display a child component app.messageComponent.
So far, everything works well except the first message in msgArray is never displayed...
Why?
Here is my app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgForOf } from '@angular/common';
import { NgModule } from '@angular/core';
import { NgModel, FormsModule } from '@angular/forms';
import { ChatComponent } from './app.chatComponent';
import { MsgComponent } from './app.msgComponent';
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
ChatComponent,
MsgComponent
],
providers: [],
bootstrap: [ChatComponent, MsgComponent]
})
export class AppModule { }
Here is my main component : app.chatComponent.ts
import { Component } from '@angular/core';
import { MsgComponent } from './app.msgComponent';
import { Msg } from './app.msgModel';
var msgArray: Msg[] = [
{ id: '11', content: 'msg0' },
{ id: '11', content: 'msg1' },
{ id: '12', content: 'msg2' },
{ id: '13', content: 'msg3' },
{ id: '14', content: 'msg4' },
{ id: '15', content: 'msg5' },
{ id: '16', content: 'msg6' },
{ id: '17', content: 'msg7' },
{ id: '18', content: 'msg8' },
{ id: '19', content: 'msg9' },
{ id: '20', content: 'msg10' }
];
@Component({
selector: 'chat-component',
templateUrl: './app.chatComponent.html',
styleUrls: ['./app.chatComponent.css']
})
export class ChatComponent {
messages: Msg[] = msgArray;
msg: Msg = new Msg();
}
app.chatComponent.html
<div>
<ul class="messages">
<msg-component *ngFor="let msg of messages" [msg]="msg.content"></msg-component>
</ul>
</div>
<input [(ngModel)]="msg.content">
Here is my child component : app.msgComponent.ts
import { Component, Input } from '@angular/core';
import { Msg } from './app.msgModel';
@Component({
selector: 'msg-component',
templateUrl: './app.msgComponent.html',
styleUrls: ['./app.msgComponent.css']
})
export class MsgComponent {
@Input() msg: Msg;
}
app.msgComponent.html
<li>{{msg}}</li>