原始变量在Angular模板中仅更新一次

问题描述 投票:0回答:1

我有一个菜单,我打开按钮点击,我想关闭内部按钮点击。当外部按钮单击时菜单打开,当我单击内部按钮时(即使控制器中的变量被切换),它也不会刷新模板中的变量。

模板

<div class="filter" (click)="openMenu()">
  <div class="inner-menu" [ngClass]="{'showMenu': showMenu }" >

  {{showMenu}} <!-- THIS DOES NOT UPDATE AFTER THE 1.TIME-->

   <div class="btn-container">
     <div class="btn tiny primary" (click)="filterData()">
       Close
     </div>
   </div> 

  </div>
 </div>

调节器

openMenu() {
  this.showMenu = true;
}

filterData() {
  this.showMenu = false;   // The value is updated in the controller
  this.applyFilter.emit(true);  // Correctly propagated to the parent
}

scss文件

filter {
position: relative;

.inner-menu {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  min-width: 25rem;

 btn-container {
   text-align: center;
   margin-top: 1.5rem;
  }
}

 .showMenu {
   display: block;
 }
}

我确信解决方案非常明显,因为我开发了许多其他应用程序并且它总是以类似的方式工作,但目前我找不到变量未在模板中更新但仅在控制器中更新的真正原因。

angular angular2-template angular2-changedetection
1个回答
0
投票

我没有使用event.stopPropagation();内部按钮单击。简单但有时不能立即找到。

我纠正了我的代码:

filterData(event: MouseEvent) {
 event.stopPropagation();  // <- This is new
 this.showMenu = false;
 this.applyFilter.emit(this.sections);
}

在模板中:

<div class="btn tiny primary" (click)="filterData($event)">
   Close
</div>

它奏效了。我希望这可以节省一些时间给别人!

UPDATE

为了完成here an article解释使用preventDefault()时的潜在危险,以便您可以了解副作用,如果您必须在您的应用程序中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.