【发布时间】:2018-02-23 16:55:31
【问题描述】:
我刚开始学习 Angular4,遇到了一个我无法解释的问题。
我现在正在尝试构建两个组件:
我的主要组件是 chatComponent 它应该显示子组件列表 msgComponent。
为此,我在 app.chatComponent 中定义了一个消息数组 msgArray,并通过 à *ngFor 指令 遍历消息。对于每条消息,我想显示一个子组件 app.messageComponent。
到目前为止,一切正常,除了 msgArray 中的第一条消息从未显示...
为什么?
这是我的 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 { }
这是我的主要组件: 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">
这是我的子组件: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>
【问题讨论】:
-
app.chatComponent.html 中有错字。应该是“让消息的味精”
-
@rjustin 你说得对,对不起,我纠正了这是一个复制/过去的错误。但这并不能解释我的问题:)
-
你能用你拥有的东西做一个 plunker 并让它运行吗?
-
@rjustin 这里是 plunker 上的演示,你可以看到我的第一条消息的内容没有显示。 (实际上第一条消息的值为null)plnkr.co/edit/mttSZ6sanD8k7GCgwUSx?p=preview
-
这是一个非常奇怪的问题。我已经看了 20 分钟了,我很困惑。它与@Input msg 为空有关。如果您设置它将显示在第一项中。这不是预期的行为。我会继续摆弄它。
标签: angular nested components ngfor