如何在不更改Angular中的URL的情况下更改组件?

时间:2017-09-19 17:26:08

标签: html angular typescript angular-ui-router

我想在不更改网址的情况下更改组件。我们假设我有一个组件register。当我打开我的网站时,我有网址www.myweb.com。然后我想点击sign up进行注册。我想在不更改网址的情况下显示我的组件register。我应该使用ngIf还是别的?你能举例说明应该怎么做吗?

更新我很抱歉,但在我看来,我被误解了。我试过了 这个解决方案:

login.component.ts:

showSignUp: boolean = false;

login.component.html:

<button (click)="showSignUp = true">Sign Up</button>

<register *ngIf="showSignUp"></register>

然而,当我点击按钮Log in时,我得到了这个:

之前: enter image description here 点击后: enter image description here 点击按钮Log in后,我想获得一个新网站,但网址相同: enter image description here

更新 您如何看待下面显示的解决方案?在html文件中,我将检查变量authenticated是否等于true。如果是,那么我将显示主页组件。

login() {
    this.loading = true;
    this.authenticationService.login(this.model.username, this.model.password)
        .subscribe(
            data => {
                this.authenticated = true;
                // this.router.navigate([this.returnUrl]);
            },
            error => {
                this.authenticated = false;
                this.alertService.error(error);
                this.loading = false;
            });
}

更新 不幸的是它没有用。任何想法如何使用此按钮?

<button [disabled]="loading" class="btn btn-primary">Log in</button>

3 个答案:

答案 0 :(得分:0)

是的,这是ngIf的完美用例。尽量不要过度设计它。

答案 1 :(得分:0)

您可以使用*ngIf并显示条件中的组件!

examle

在您的注册组件中,设置变量并在点击注册按钮时更改其值。通过点击显示中的条件

,在点击登录时显示您的注册组件
// sign up component 

showRegister = false;

在您的注册组件html中

<register *ngIf="showRegister"></register>

答案 2 :(得分:0)

ngIf是继续这种事情的方式。

只需输入类似

的组件代码即可
showSignUp: boolean = false;

然后在模板中:

<button (click)="showSignUp = true">Sign Up</button>

<register *ngIf="showSignUp"></register>

既然您对Angular不熟悉,我会提到为了在模板中使用ngIf,您的模块需要导入CommonModule,如

import { CommonModule } from '@angular/common';

imports: [
   CommonModule,
]
相关问题