子组件中的事件发射器不刷新父 ngIf (Angular 9) 中的值



我有一个带有子组件的 Angular 模块。此组件显示使用 GSAP 库制作的动画,当它结束时,它应该隐藏此组件并显示一个网页。

子组件

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { gsap } from "gsap";
@Component({
selector: 'child-component',
templateUrl: 'child-component.html',
styleUrls: ['child-component.css']
})
export class ChildComponent implements OnInit {
@Output() public show = new EventEmitter<boolean>();
constructor() { }
ngOnInit(): void {
var tl = gsap.timeline();
var arg = this.show;
gsap.set("#animation", ...);
...
gsap.set("#animation", { duration: 2, delay: 10, onCompleteParams: [arg], onComplete: this.endAnimation });
tl.play();
}
public endAnimation(status: EventEmitter<boolean>): void {
status.emit(false);
}

应用组件

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: 'app.html',
styleUrls: ['app.css']
})
export class AppComponent {
public title = 'mySite';
public showAnimation: boolean = true;
constructor( ){
}
public hideAnimation(value: boolean) {
this.showAnimation = value;
}
}

父模板:

<child-component (show)="hideAnimation($event)" *ngIf="showAnimation"></child-component>
<div class="webpage" *ngIf="!showAnimation">
...
</div>

这里的问题是 EventEmitter 将值发送到父组件,但由于某种原因,此值不会更新,动画也不会隐藏。 恐怕我错过了一些微不足道的错误,应该很快解决。如果有人能解决这个问题,我将不胜感激。 注意:我使用的是 Angular 9。

我认为从 gsap 调用endAnimation会脱离 Angular 区域,并且在触发hideAnimation更新showAnimation后不会发生更改检测调用,因此您有一些选择

1( 使用ChangeDetectorRef

constructor(private cd: ChangeDetectorRef) {
}
public hideAnimation(value: boolean) {
this.showAnimation = value;
this.cd.detectChanges();
}

2(使用NgZone

constructor(@Inject(ElementRef) private elementRef: ElementRef, private zone: NgZone) { }
ngOnInit() {
var arg = this.show;
gsap.from("#logo", { duration: 3, x: 300, opacity: 0, scale: 0.5, 
onCompleteParams: [arg,this.zone], onComplete: this.endAnimation });
}
public endAnimation(status: EventEmitter<boolean>,zone): void {
zone.run(() => {
status.emit(false)
})
}

您的 EventEmitter 变量是

@Output() public show = new EventEmitter<boolean>();

但你正在发出这样的价值。

public endAnimation(status: EventEmitter<boolean>): void {
status.emit(false);
}

状态是一个局部变量。

你应该这样做。

public endAnimation(): void {
this.show.emit(false);
}

如果您有任何疑问,请告诉我。

最新更新