【问题标题】:Angular2 - ngIf does not re-render the child componentAngular2 - ngIf 不会重新渲染子组件
【发布时间】:2017-05-31 07:56:54
【问题描述】:

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

登录组件:

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

我已将我的登录组件放在我父母的组件中,例如:

<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。我希望角度会在更新 *ngIf 并重新打开模式时重绘,但事实并非如此。它只工作一次(即使我在将 showLoginModal 设置为 true 之前将其重置为 false)。

【问题讨论】:

  • 尝试注入cdRef:ChangeDetectorRef并将其设置为false,然后设置为true,并在两者之间调用更改检测,如this.showLoginModal = false;this.cdRef.detectChanges();this.showLoginModal = true;
  • 您是否尝试将 showLoginModal 设置为 PUBLIC ?
  • @federicoscamuzzi 将其设置为公开无效。
  • @GünterZöchbauer 按照您的建议实施变更检测器很有效,非常感谢!

标签: angular


【解决方案1】:

注入cdRef:ChangeDetectorRef

constructor(private cdRef:ChangeDetectorRef)  {}

并将showLoginModal 设置为false,然后设置为true,并在两者之间调用更改检测

this.showLoginModal = false;
this.cdRef.detectChanges();
this.showLoginModal = true;

这样ngIf 将重新渲染,即使在调用submitBid() 方法之前showLoginModaltrue

【讨论】:

    猜你喜欢
    • 2020-02-13
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2017-06-09
    • 2021-01-24
    • 2018-09-01
    • 2019-10-05
    相关资源
    最近更新 更多