ngif导致页面重新加载 - Angular 2

时间:2016-09-01 23:06:44

标签: angular

我在收到搜索结果时试图显示一个组件,导致事件发射器关闭,导致onResultsRecieved()执行。

然而该页面只是重新加载。所以我调试了它,当代码进入onResultsRecieved()时,当它运行this.results.scroll()时,它会导致一个异常,说明" TypeError:无法读取属性'滚动'未定义"然后页面重新加载。

scroll()是结果viewchild的一种方法。

为什么results未定义?为什么异常永远不会在控制台中显示,而是重新加载页面?

所涉及的所有代码:

找到-page.component.html

<div id="find-page">
   <find-form (onResultsRecieved)="onResultsRecieved($event)"></find-form>
</div>
<results-div #results *ngIf="showResults"></results-div>

找到-page.component.ts

import { Component, ViewChild } from '@angular/core';
import { NavbarComponent } from '../shared/navbar.component';
import { FindFormComponent } from '../find-page/find-form.component';
import { ResultsComponent } from '../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 } from '@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>

相关的css:

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

1 个答案:

答案 0 :(得分:4)

看来你正在使用一个表单,但是,我没有看到任何地方附带的实际代码,所以这只是一个有根据的猜测。我遇到了一个非常类似的问题(我偶然发现了这个问题),并且很容易修复。

当您提交表单时,它会尝试将您带到action属性定义的任何位置,即使没有操作属性(在这种情况下表单只是重新加载当前页面)。为避免这种情况,请在表单标记中添加onSubmit="return false;",这样可以防止表单在提交表单后尝试更改页面。

希望这有帮助。

相关问题