gpt4 book ai didi

Angular2 - ngIf 不重新渲染子组件

转载 作者:行者123 更新时间:2023-12-04 14:27:52 25 4
gpt4 key购买 nike

我有一个从多个地方调用的登录组件,并有一个输入将其显示为模态组件或只是普通组件。

登录组件:

declare var jQuery: any;
@Component({
selector: 'login-view',
templateUrl: '/login/index.html',
inputs: ['isOpenLoginModal']
})
export class LoginComponent extends BaseConfigurations {
public isOpenLoginModal: boolean;

//this method is called from ngOnInit in base class
public initialize() {
this.showModal();
}

constructor() {
super();
}

private showModal(): void {
if (this.isOpenLoginModal) {
jQuery("#loginComponentModal").modal('show');
}
}
}

我的 Login/index.html 模板包含一个简单的引导模式。

我的父组件:
@Component({
selector: 'upcoming-auction-view',
templateUrl: '/auctions/upcoming-auctions.html'
})
export class UpcomingAuctionsComponent extends BaseConfigurations {
private showLoginModal: boolean = false;

public initialize() {
this.showLoginModal = false;
}

constructor() {
super();
}

submitBid(): void {
if (!this.isAuthenticated) {
//if user is not authenticated, show login component
this.showLoginModal = true;
}
}
}

我已经将我的登录组件放在我 parent 的组件中,例如:
<login-view *ngIf="showLoginModal === true" [isOpenLoginModal]="true"></login-view>

并有一个按钮调用 submitBid 函数并更新标志
<input type="submit" class="form-submit primary-btn" value="Place Bid" (click)="submitBid()" />

我正在根据用户是否通过身份验证更新“showLoginModal”,并让 *ngIf 使用模式选项重新呈现 LoginComponent。我希望 angular 在 *ngIf 更新并重新打开模态时重绘,但事实并非如此。它只能工作一次(即使我在将 showLoginModal 设置为 true 之前将它重置为 false)。

最佳答案

注入(inject)cdRef:ChangeDetectorRef

constructor(private cdRef:ChangeDetectorRef)  {}

并设置 showLoginModalfalse然后到 true在两者之间调用更改检测
this.showLoginModal = false;
this.cdRef.detectChanges();
this.showLoginModal = true;

这样 ngIf即使 showLoginModal 也会重新渲染是 true之前 submitBid()方法被调用。

关于Angular2 - ngIf 不重新渲染子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41677060/

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