无法使用角度2数据绑定输出消息

时间:2018-02-03 06:27:17

标签: angular

我似乎无法使用消息显示文本:Message = new Message(),它只是空白而且我也得到控制台错误,说无法读取未定义的属性'content'。

我当前的消息.model.ts:

export class Message {
 content: string;
 username: string;
 messageId?: string;
 userId?: string;

 constructor(content: string, username: string, messageId?: string, userId?: string) {
   this.content = content;
   this.username = username;
   this.messageId = messageId;
   this.userId = userId;
 }
}

message.component.ts:

import { Component, Input } from '@angular/core';
import { Message } from './message.model';

@Component ({
 selector: 'app-message',
 templateUrl: './message.component.html',
 styles: [`
   .author {
     display: inline-block;
     font-style: italic;
     font-size: 12px;
     width: 80%;
   }
   .config {
     display: inline-block;
     text-align: right;
     font-size: 12px;
     width: 19%;
   }
 `]

})
export class MessageComponent {
 @Input() message: Message;
}

app.component.ts:

import { Component } from '@angular/core';
import { Message } from './messages/message.model';

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html'
})

export class AppComponent {
 message: Message = new Message("this is the content", "Some guy");
}

app.component.html

<div class="container">
 <div class="row">
   <div class="col-md-8 col-md-offset-2">
     <app-message [message]="message"></app-message>
   </div>
 </div>
</div>

message.component.html

<article class="panel panel-default">
  <div class="panel-body">
    {{ message.content }}
  </div>
  <footer class="panel-footer">
    <div class="author">
      {{ message.username }}
    </div>
    <div class="config">
      <a href="#" (click)="onEdit()">Edit</a>
      <a href="#">Delete</a>
    </div>
  </footer>
</article>

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MessageComponent } from './messages/message.component';

@NgModule({
    declarations: [
        AppComponent,
        MessageComponent
    ],
    imports: [BrowserModule, FormsModule],
    bootstrap: [AppComponent, MessageComponent]
})
export class AppModule {

}

1 个答案:

答案 0 :(得分:0)

创建视图后将分配传递的message参数。您可以强制使用*ngIf仅在分配了消息时显示模板

<article *ngIf="message" class="panel panel-default">
  <div class="panel-body">
    {{ message.content }}
  </div>
  <footer class="panel-footer">
    <div class="author">
      {{ message.username }}
    </div>
    <div class="config">
      <a href="#" (click)="onEdit()">Edit</a>
      <a href="#">Delete</a>
    </div>
  </footer>
</article>

你也可以简短地写下你的课程

export class Message {

   constructor(public content: string, 
               public username: string, 
               public messageId?: string, 
               public userId?: string) { }
}