Paco Pinazo Guna
Paco Pinazo Guna

Reputation: 117

Angular router-outlet is appending rather than replacing the entire component

I am trying to make a route between two components in Angular 9.

The problem is that when I route it append rather than replacing the entire component.

Main page

I want to replace the main page with the text below

App-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BookComponent } from './components/book/book.component';


const routes: Routes = [

  { path: 'autorBuscado', component:BookComponent,pathMatch:'full'}
];

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

Any Ideas? If you need more code tell me!

App.component.html

<router-outlet><h1>Autores</h1>
<div *ngFor='let autor of autores'>
  <tr>{{ autor["id"] }} {{ autor["firstName"] }} {{ autor["lastName"] }}</tr>
</div>

<form>
  <label for="autor">¿Que autor desea buscar?</label>
  <input name="autor" type="text" [(ngModel)]="autorBuscado">
  <input (click)="detalleAutor()" type="button" id="enviar" value="Buscar">
</form>

<h1>Libros</h1>
<div class="principal">
  <div *ngFor='let libro of libros'>
    <div class="libros">
      <img class="imagenLibro" src='assets/imagenes/{{libro.id}}.png' alt="aaaa">
      <p>Título: {{ libro["name"] }}</p>
    </div>
  </div>
</div>
</router-outlet>

Upvotes: 0

Views: 1872

Answers (1)

Vinaayakh
Vinaayakh

Reputation: 522

Create a new Component HomeComponent with the HTML content as

<h1>Autores</h1>
<div *ngFor='let autor of autores'>
  <tr>{{ autor["id"] }} {{ autor["firstName"] }} {{ autor["lastName"] }}</tr>
</div>

<form>
  <label for="autor">¿Que autor desea buscar?</label>
  <input name="autor" type="text" [(ngModel)]="autorBuscado">
  <input (click)="detalleAutor()" type="button" id="enviar" value="Buscar">
</form>

<h1>Libros</h1>
<div class="principal">
  <div *ngFor='let libro of libros'>
    <div class="libros">
      <img class="imagenLibro" src='assets/imagenes/{{libro.id}}.png' alt="aaaa">
      <p>Título: {{ libro["name"] }}</p>
    </div>
  </div>
</div>

Change App.component.html to

<router-outlet></router-outlet>

Change App-routing.module.ts to

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { BookComponent } from './components/book/book.component';


const routes: Routes = [
  { path: '', component:HomeComponent,pathMatch:'full'},
  { path: 'autorBuscado', component:BookComponent,pathMatch:'full'}
];

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

Upvotes: 1

Related Questions