在 Angular 中发出值,记录为 [object Object] 而不是 value

emitting value in Angular, logged as [object Object] rather than value

我在 child/parent 值传递方面取得了一些进展,并且我一直在关注这个 youtube 视频 (https://www.youtube.com/watch?v=tZNWv-iW74I),而且我正在慢慢实现。目前,我似乎无法像我想的那样向父组件发出值,我只能发出未定义的对象,我哪里出错了?在我学习的过程中只需要一个友好的推动。

我正在尝试做的事情 - 移动滑块,然后 stats.component.html 中的 showValue 更新为滑块设置的值。

app.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],

})

export class AppComponent
{
@Output() slider1Change: EventEmitter<number> = new EventEmitter<number>();

onInputChange(event: any)
{
 console.log("This is emitted as the thumb slides " + event.value);
 this.slider1Change.emit(event.value)
 console.log("This is emitted via @Output " + this.slider1Change);
}
}

export class SliderFormattingExample
{
formatLabel(value: number)
{
  if (value >= 1000) {
    return Math.round(value / 1000) + 'k';
}
 return value;
}
}

日志看起来像这样,第二个控制台输出发出的不是值而是对象:

This is emitted as the thumb slides 19550

This is emitted via @Output [object Object]

This is emitted as the thumb slides 19622

app.component.html

<h1>Hello app-component.html!</h1>

<h2>Slider Test</h2>
<mat-slider id="slider1" min="18296" max="23456" thumbLabel step="1" value="1" (input)="onInputChange($event)">
</mat-slider> <br />
<mat-slider id="slider2" min="12000" max="14000" thumbLabel step="1" value="1" (input)="onInputChange($event)">
</mat-slider>

<app-stats></app-stats>

stats.component.html

<h1>statsComponent</h1>
<p>{{ showValue }}</p>
<div (notify) = "onValueChanged($event)"></div>

stats.component.ts

import { Input, Output, Component, OnInit } from '@angular/core';

@Component({
selector: 'app-stats',
templateUrl: './stats.component.html',
styleUrls: ['./stats.component.scss'],

})
export class StatsComponent implements OnInit {

showValue: number = 99999;

onValueChanged(sliderVal: number): void
{
 this.showValue = sliderVal;
}

constructor() { }

ngOnInit(): void {
}

}

console.log("This is emitted via @Output:", this.slider1Change);

问题出在 console.log(<string> + <object>)。这会在您的对象被控制台解析之前将其转换为字符串。

为了记录对象,您需要使用逗号分隔符:console.log(<string>, <object>).

对于您的示例,您将使用:

console.log("This is emitted as the thumb slides ", event.value)console.log("This is emitted via @Output ", this.slider1Change)