簡體   English   中英

Angular 在按鈕單擊時從一個組件移動到另一個組件

[英]Angular moving from one component to another on button click

我想在單擊按鈕時從一個 angular 組件導航到另一個組件。 我有兩個組件 app 和 login。單擊 app.component.html 中的按鈕時,我想導航到 login.component.html。 這是我嘗試過的。 雖然 URL 正在更改,但我看不到頁面的 html 內容。

app.component.html

<div class="row">
        <div class="col-xs-9"></div>
    <div class="col-xs-3">

    <input type="button" class="btn btn-primary pull-right" (click)="onSubmit()" value="Next">

    </div>
</div>

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LogInComponent } from './components/log-in/log-in.component';

const routes: Routes = [{ path: 'login', component: LogInComponent }];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private router: Router, ) {}  
    onSubmit() {  
        this.router.navigate(['/login'])  
    }  
    ngOnInit() {}  
}

登錄.component.html

<p>it works</p>

在按鈕上單擊 URL 更改為 /login。 但是我仍然看到按鈕 UI,但它不起作用。 任何幫助將不勝感激。!在此先感謝。

我認為這會奏效。

這是您的解決方案:

onSubmit() {  
     this.router.navigateByUrl('/login');
} 

另一種方法是:

<button class="nav-item" [routerLink]="['/login']"> Login </button>

添加您的組件:

<router-outlet></router-outlet>

關於您的代碼,我想念一些事情。 其一, app.routing.module需要在 app.module.ts 中導入注冊:

import { AppRoutingModule } from './app-routing.module';

  imports: [
    BrowserModule,
    AppRoutingModule,
    ...
 ]

另一方面,我沒有看到路由器插座:

<router-outlet></router-outlet>

我建議你使用 app 組件 (app.componet.html) 可能是這樣的:

<app-navbar></app-navbar> // if you use one
<router-outlet></router-outlet> // this is where the routing happens

index.html你引用 app.component 就像這樣:

<body>
  <app-root></app-root>
</body>

那么 Kishan Patel 建議的兩個選項都應該有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM