How do I pass an object to Angular with the @ Output() decorator?
The object transfer is registered in this file, but the code does not work correctly, "[object Object] " is output, how can I fix it? Please help me figure it out
//child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child',
template: '<div><input class="form-control" [(ngModel)]="user" placeholder = "Введите сообщение" />
<button class="btn btn-default" (click)="adding(user, bot)">Отправить</button></div>',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Output('AddMessage') addMessage = new EventEmitter<object>()
public adding(user_mes: string, bot_mes: string) {
this.addMessage.emit({user_mes, bot_mes});
}
}
//two.component.ts
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'two',
template: `<h4>Список сообщений</h4>
<ul *ngFor="let msg of message"><li>{{msg.user}}</li><li>{{msg.bot}}</li></ul>`,
styles: [ '' ]
})
export class TwoComponent {
@Input() message: string[];
}
//app.component.ts
import { Component } from '@angular/core';
class Messages {
user: string;
bot: string;
constructor(_user: string, _bot: string) {
this.user = _user;
this.bot = _bot;
}
}
@Component({
selector: 'my-app',
template: '<two [message]="message"></two>
<child (AddMessage)="addMessage($event)"></child>',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public message: Messages[] = [];
addMessage(user: string, bot: string) {
if (user == null) {
return;
}
this.message.push(new Messages(user, bot));
}
}
0
Author: Татьяна Атласова, 2019-02-14
1 answers
You are passing an object, but you want to accept two strings! And with the fields user_mes
and bot_mes
.
Rewrite it like this:
addMessage(event: any) {
const { user_mes, bot_mes } = event;
if (user_mes == null) {
return;
}
this.message.push(new Messages(user_mes, bot_mes));
}
0
Author: Hooter, 2019-02-14 09:38:12