我只想在单击子组件中的按钮时更新父组件中的布尔值 . 我有一个基于动态ngClass隐藏和显示的滑出式子组件 . 该类是根据父级的布尔值设置的 . 但是,当我从子项中的按钮关闭该组件时,我想更新父项中的布尔值:
父组件打字稿:
export class AppComponent implements OnInit {
showFlyout: boolean
constructor() {}
ngOnInit() {
this.showFlyout = false;
}
}
和父html:
<main>
<button (click)="showFlyout = !showFlyout"><i class="fa fa-check"></i>Show Flyout</button>
{{showFlyout}}
<app-child id="flyout" [ngClass]="showFlyout ? 'active' : ''"></app-child>
</main>
子组件打字稿:
export class ActivateFlyoutComponent implements OnInit {
constructor() { }
ngOnInit() {
}
closeActivationFlyout() {
const flyout = document.getElementById('flyout');
flyout.classList.remove('active');
}
}
和子组件html:
<button (click)="closeFlyout()">Close</button>
这是Stackblitz . 您可以看到正确单击父按钮切换类但是如何从子项中单击更新该布尔值,因此在子组件中不需要使用closeActivationFlyout()方法?
2 回答
像其他人提到的那样使用
@Output()
,但它需要发出一个事件,你还需要检查在父html中触发的事件 .这是一个工作StackBlitz
在子组件中 .
并在父组件html中 .
您还可以在父组件中创建一个函数,并触发
(onCloseClick)="doFunction()"
您可以使用双向数据绑定使其工作:
AppComponent:
ChildComponent:
https://stackblitz.com/edit/angular-v95emc?file=app%2Fchild-component%2Fchild.component.ts