испуская значение в Angular, регистрируется как [объект объекта], а не как значение - PullRequest
2 голосов
/ 02 марта 2020

Я добился некоторого прогресса в передаче значений дочерних / родительских функций, и я следил за этим видео на YouTube (https://www.youtube.com/watch?v=tZNWv-iW74I), и мне не терпится попасть туда. В настоящий момент я не могу передать значение, как хотелось бы родительскому компоненту, я могу только выдать неопределенный объект, есть идеи, где я ошибаюсь? Просто нужно дружеским толчком, как я учусь, пожалуйста.

Что я пытаюсь сделать - ползунок перемещается, затем showValue в stats.component. html обновляется значением, которое ползунок имеет установить на.

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 {
}

}

Ответы [ 2 ]

1 голос
/ 02 марта 2020

Проблема с 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)

1 голос
/ 02 марта 2020

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

...