【发布时间】:2018-11-02 00:17:31
【问题描述】:
我的 Angular 2 项目中有 2 个组件。 第一个组件是:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'second-component',
template: '<div><div>'
})
export class SecondComponent implements OnInit{
@Output() changeDetect = new EventEmitter<Boolean>();
private value: boolean;
ngOnInit() {
this.value = false;
this.doSomething();
}
doSomething(): void {
if (2 > 1) {
this.value = true;
}
}
changeDetection() {
this.changeDetect.emit(this.value);
}
}
我需要做的是,我需要在第二个组件中发送this.value 值。
例如方法doSomething() 做了一些改变this.value,它可能是真或假,不管。
第二部分:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'first-component',
template: '
<div>FIRST COMPONENT<div>
<second-component (changeDetect)="changes($event)"></second-component>
<span>{{_message}}
</span>'
})
export class FirstComponent implements OnInit {
private _change: boolean;
private _message: string;
ngOnInit() {
}
changes(event) {
// Here i want to get boolean value from the first component to do something like below
if (event === true) {
message = 'true';
}
}
}
我知道我的问题很菜,但我希望你明白我的意思。
任何建议我都会很高兴,因为我完全迷失了。
【问题讨论】:
-
你是说事件没有发送到子组件中?
-
目前发生了什么?发出的值不是布尔值吗?
-
一般情况下,使用 console.log 或浏览器中的调试工具来帮助诊断任何 typescript/javascript 问题。
-
小心命名
changeDetection之类的东西,因为 Angular 2+ 允许您注入changeDetectorRef,这很可能会让您或其他人感到困惑,这使您可以控制更改检测。这与通过EventEmitter发出事件非常不同。
标签: angular typescript