1

I developed this app (http://www.anelmad.com) and I am trying to redirect the display of information (dictionary definitions of words) upon submit (Enter or button click) into another page.

The redirection works but the content of the page does not follow.

in home.component.html:

<form #myForm>
     (...)

    <input type="text" class="form-control" #elem 
    (keyup)="onNameKeyUp(elem.value)"
    [ngModelOptions]="{standalone: true}"
    [(ngModel)]="latinButton"
    (focus)="onNameKeyUp(elem.value)"
    placeholder="Enter"/>

    <span class="input-group-append">
        <button class="btn btn-outline-secondary" type="submit" 
    (click)="getWordList()">
            <i class="fa fa-search"></i>
        </button>
      </span>

After this form, I added:

 <router-outlet></router-outlet>

Inside home.component.ts, I added (this.router.navigate) with the new page as an argument:

  getWordList(){
  this.router.navigate(['/words']);
  this.webservice.getWords(this.spelling, this.selected)
  .subscribe((res: Array<Word>)=> {
  (...)

in app.module:

const myRoutes: Routes=[
  {path: 'words', component: WordsComponent},
  {path: 'about', component: AboutComponent},
  {path: 'home', component: HomeComponent},
  {path: '', redirectTo: '/home', pathMatch:'full'},
  {path: '**', redirectTo: '/home', pathMatch:'full'

]

How do I pass the information to be displayed from the form into the new page (words.component.html)?

omar
  • 401
  • 1
  • 7
  • 26

1 Answers1

0

There are numerous ways to pass data from one component to another routed component:

  • Build a service: From the first component, set the data into the service. From the second component, read the data from the service. Since an Angular service is a singleton (when the service is registered with the root injector), it is shared between all of the components.

I have a working stackblitz demonstrating this here: https://stackblitz.com/edit/angular-simpleservice-deborahk

The example uses a simple input element, but you could expand it to include all of the form data.

  • Use route parameters: If you just need to pass a single item or a few items, you can use route parameters. Angular provides required, optional, and query parameters that can be used to pass data on the route from one component to another.

  • New State property: Use the new Angular v7.2 feature that allows passing state between routes. See this link for more information about this last option: https://netbasal.com/set-state-object-when-navigating-in-angular-7-2-b87c5b977bb

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • Thanks for the answer. I tried the first option but I'm getting this error: Form submission canceled because the form is not connected – omar Feb 01 '19 at 01:12
  • Have you seen this: https://stackoverflow.com/questions/42531167/angular-2-form-submission-canceled-because-the-form-is-not-connected – DeborahK Feb 01 '19 at 02:19