【问题标题】:Primitive variable updated only once in Angular template原始变量在 Angular 模板中仅更新一次
【发布时间】:2019-02-25 16:48:17
【问题描述】:

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

模板

<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;
 }
}

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

【问题讨论】:

  • 试试:(click)="filterData(); $event.stopPropagation();"。点击事件很可能也被父div捕获,触发(click)="openMenu()"并再次将showMenu设置为true
  • @Connors:我刚刚发现这就是原因 :) 但是感谢您的提示!!

标签: angular angular2-template angular2-changedetection


【解决方案1】:

我没有使用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>

它奏效了。我希望这可以为其他人节省一些时间!

更新

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多