以Angular形式发射值,记录为[object Object]而不是value

问题描述 投票:0回答:2

我在传递儿童/父母价值观方面取得了一些进展,而且我一直在关注这个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;
}
}

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

这在拇指滑动19550时发出

这通过@Output [对象对象]发出

随着拇指滑行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 {
}

}
angular typescript eventemitter
2个回答
0
投票

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


0
投票

问题出在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)

© www.soinside.com 2019 - 2024. All rights reserved.