我正在使用Angular 4
实现一个简单的登录/注册应用。我想要实现的是使用显示登录表单的默认视图,只有当我点击 Register 链接时,我才想显示注册表单,必须替换登录表单。 />
现在我必须点击登录链接才能显示它。我会粘贴一些代码。
应用模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { AppComponent } from './components/app/app.component';
import { LoginComponent } from './components/login/login.component';
import { RegisterComponent } from './components/register/register.component';
import { HomeComponent } from './components/home/home.component';
import { UserService } from './services/user/user.service';
import { User } from './services/user/user';
@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
},
{
path: 'home',
component: HomeComponent
}
])
],
declarations: [
AppComponent,
LoginComponent,
RegisterComponent,
HomeComponent
],
providers: [UserService, User],
bootstrap: [AppComponent]
})
export class AppModule { }
应用组件模板
<div id="container">
<div id="parent">
<div id="left"></div>
<div id="right">
<nav>
<a routerLink="/login" routerLinkActive="active">Login</a>
<a routerLink="/register" routerLinkActive="active">Register</a>
</nav>
<router-outlet></router-outlet>
</div>
</div>
</div>
登录组件模板
<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
<div>
<label for="username">Username</label>
<input id="username" name="username" ngModel #username="ngModel">
</div>
<div>
<label for="password">Password</label>
<input id="password" name="password" ngModel #password="ngModel">
</div>
<span *ngIf="onSubmit(loginForm)">true</span>
<button>Login</button>
</form>
注册组件模板
<form #registerForm="ngForm" (ngSubmit)="onSubmit(registerForm)">
<div>
<label for="name">Nome</label>
<input id="name" name="name" ngModel #name="ngModel">
</div>
<div>
<label for="lastName">Cognome</label>
<input id="lastName" name="lastName" ngModel #lastName="ngModel">
</div>
<div>
<label for="username">Username</label>
<input id="username" name="username" ngModel #username="ngModel">
</div>
<div>
<label for="password">Password</label>
<input id="password" name="password" ngModel #password="ngModel">
</div>
<div>
<label for="passwordRep">Ripeti la password</label>
<input id="passwordRep" name="passwordRep">
</div>
<button>Registrati</button>
</form>
我缺少一些Router Module
设置吗?
提前谢谢。
答案 0 :(得分:0)
在您的路由中,如果您希望将其作为默认视图,则需要 redirect 将用户添加到login
页面。请尝试以下方法:
RouterModule.forRoot([
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
},
{
path: 'home',
component: HomeComponent
}
])