简体   繁体   中英

Using *ngIf in Angular not working

I'm new to Angular so struggling with something I think is pretty basic.

I have a component that has the following html:

<div *ngIf="this.showWelcome" class="popup-modal-wrap">
    <h3>Hi {{this.currentUser.firstName}}, welcome!</h3>
    <a (click)="this.showWelcome = false" class="button naked">Close</a>
</div>

The component itself looks like this:

export class HomeLayoutComponent implements OnInit {

    showWelcome = false;

    public currentUser: LoggedInUser;

    constructor(private userService: UserService, private router: Router) {
    }

    ngOnInit() {
        if (this.router.url == '/welcome') {
            this.userService.getCurrentUser()
                .subscribe(
                    currentUser => {
                        this.currentUser = currentUser;
                        this.showWelcome = true;
                    },
                    error => {
                        console.log(error);
                    }
                );
        }
    }
}

This code doesn't work, the popup doesn't show. It appears that once I set the showWelcome to true, it doesn't do anything as the page has already rendered.

The following code works fine:

if (this.router.url == '/welcome') {
    this.showWelcome = true;
}      

So I'm sure I'm dealing with an async issue of some sort

The problem was that when I came from my registration page, this.router.url was set to the old route, not the new one.

When testing I was going straight to the /welcome url which was why it was working

With *ngIf, this.showWelcome wont work. For Data binding, you just need to put it as *ngIf="showWelcome" in your HTML template

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM