ngif causing page to reload - Angular 2 -


i'm trying display component when search results recieved, causing event emitter go off, causing onresultsrecieved() execute.

however page reloads. debugged it, , when code goes onresultsrecieved(), when runs this.results.scroll() causes exception says "typeerror: cannot read property 'scroll' of undefined" , page reloads.

scroll() method on results viewchild.

why results undefined? , why exception never show in console, , instead reload page?

all code involved:

find-page.component.html

<div id="find-page">    <find-form (onresultsrecieved)="onresultsrecieved($event)"></find-form> </div> <results-div #results *ngif="showresults"></results-div> 

find-page.component.ts

import { component, viewchild } '@angular/core'; import { navbarcomponent } '../shared/navbar.component'; import { findformcomponent } '../find-page/find-form.component'; import { resultscomponent } '../find-page/results.component';  @component({    selector: 'find-page',    templateurl: 'app/find-page/find-page.component.html',    styleurls: ['app/find-page/find-page.component.css' ],    directives: [ findformcomponent, resultscomponent ] }) export class findpagecomponent {    showresults = false;     @viewchild('results') results;       onresultsrecieved(recieved: boolean) {         if ( recieved ) {            this.showresults = true;            this.results.scroll();         }else {            this.showresults = false;         }   } } 

results.component.ts:

import { component, afterviewinit } '@angular/core';  @component({    selector: 'results-div',    templateurl: 'app/find-page/results.component.html',    styleurls: ['app/find-page/results.component.css' ] }) export class resultscomponent implements afterviewinit {     ngafterviewinit() { scrolltoanchor.gototargetbottom("#results-page");    }     scroll() {       scrolltoanchor.gototargetbottom("#results-page");    } }  results.component.html:  <div id="results-page"></div> 

relevant css:

#results-page {   overflow-y: auto;   overflow-x: hidden;   display: flex;   flex-direction: column;   justify-content: center;   padding-top: 50px; } 

it appears using form, however, don't see actual code attached anywhere going have educated guess. having similar problem (which how stumbled across question), , fixed easily.

when submit form try take wherever action attribute defines, if there no action attribute (in case form reloads current page). avoid this, add onsubmit="return false;" form tag, prevent form attempting change page once form submitted.

hope helps.


Comments