Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - ngIf does not re-render the child component

Tags:

angular

I have a login component which is being called from multiple places and has an input to show it as modal or just plain component.

LoginComponent:

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

My Login/index.html template contains a simple bootstrap modal.

My parent component:

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

I have placed my login component in my parent's component like:

<login-view *ngIf="showLoginModal === true" [isOpenLoginModal]="true"></login-view>

and have a button which calls the submitBid function and updates the flag

<input type="submit" class="form-submit primary-btn" value="Place Bid" (click)="submitBid()" />

I am updating 'showLoginModal' based on if the user is authenticated or not and have *ngIf to re-render the LoginComponent with modal option. I expect the angular to redraw the when *ngIf is updated and reopen the modal but it doesn't. It only works once (even if i reset showLoginModal to false before setting it to true).

like image 939
Ali Baig Avatar asked Oct 23 '25 14:10

Ali Baig


1 Answers

Injecting cdRef:ChangeDetectorRef

constructor(private cdRef:ChangeDetectorRef)  {}

and set showLoginModal to false and then to true with calling change detection in between like

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

This way ngIf will re-render even when showLoginModal was true before the submitBid() method was called.

like image 142
Günter Zöchbauer Avatar answered Oct 26 '25 14:10

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!