gpt4 book ai didi

angular - @Output 改变 bool 状态

转载 作者:行者123 更新时间:2023-12-02 16:15:34 24 4
gpt4 key购买 nike

我正在尝试将 bool 值的状态从子级更改为父级。这就是我到目前为止所拥有的。

子组件

@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}} 发生变化。任何帮助都会很棒,谢谢。

最佳答案

1) 当您有父子场景时,@Input@Output将起作用。我认为你没有!
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;
}

child

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);
}
}

关于angular - @Output 改变 bool 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39797056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com