我正在尝试将布尔值的状态从子级更改为父级。这是我到目前为止所做的。
子组件
@Input() state: boolean;
@Output() show = new EventEmitter();
@Output() hide = new EventEmitter();
onHover() {
this.state = true;
this.show.emit(this.state);
console.log("state is " + this.state);
}
onHoverOut() {
this.state = false;
this.hide.emit(this.state);
console.log("state is " + this.state);
}
child.html
<a (mouseover)="onHover(show.state)" (mouseleave)="onHoverOut(hide.state)">random Link</a>
父组件
@Component({
selector: 'my-app',
template: '<h3 (show)="toggleState" (hide)="toggleState">toggle state: {{boolshow}}</h3>',
})
export class AppComponent {
toggleState: boolean;
boolshow = this.toggleState;
}
当我悬停在链接上时,我没有看到{{boolshow}}发生变化。任何帮助都会很棒,谢谢。
答案 0 :(得分:8)
1) <输入和 @Output 将在您有 Parent&amp;儿童 情景。我不认为你拥有它! 2)当事情可以如此简单地显示时,你正在处理这么多事情。
工作演示:https://plnkr.co/edit/AsmA5DGYTNZNLEAd2O7s?p=preview
注意:在这里,我已将其优化到一定程度。我仍然可以超越这个,但出于理解的目的,我认为就是这样。
<强>父强>
import { Component, ElementRef,Renderer } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h3>toggle state: {{boolshow}}</h3>
<child [state]="boolshow" (toggle)="boolshow=$event" ></child> //<<<=== here we have set parent relation with child component
`,
})
export class AppComponent {
boolshow = true;
}
儿童强>
import { Component, ElementRef,Renderer,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'child',
template: `
<a (mouseover)="onHover()" (mouseleave)="onHoverOut()">random Link</a>
`
})
export class Child {
@Input() state: boolean;
@Output() toggle = new EventEmitter();
onHover() {
this.state = true;
this.toggle.emit(this.state);
console.log("state is " + this.state);
}
onHoverOut() {
this.state = false;
this.toggle.emit(this.state);
console.log("state is " + this.state);
}
}