angular - 在 Angular 中发出值,记录为 [object Object] 而不是值
问题描述
我在孩子/父母价值传递方面取得了一些进展,我一直在关注这个 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 [object Object] 发出的
这是拇指滑动时发出的 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(<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)
推荐阅读
- c - 从包含整数的文件中读取一行
- loops - ansible 循环遍历文件列表并检查文件是否存在,如果不下载它
- php - woocommerce 无法为 function.php 生成通用函数
- java - java教科书帮助中的推回流示例。到底是怎么回事?
- assembly - 代码正在运行,但没有在 emu8086 中显示任何输出
- javascript - 尝试在反应应用程序中连接到 mongodb 时,应用程序崩溃并出现错误:无法获取未定义或空引用的属性“替换”
- javascript - React-select 不渲染数据
- lua - 为什么stdin在显示文本时返回错误?
- ios - 如何在 ARKit 中放置自定义对象(.scn)?
- javascript - 如何跟踪消息的反应次数?