【问题标题】:Angular2(v4.2.5) click event doesn't work inside *ngIFAngular2(v4.2.5) 点击事件在 *ngIF 中不起作用
【发布时间】:2017-07-07 23:54:28
【问题描述】:

我在 Angular 中有以下问题:据我所知,*ngIf 指令不允许我在嵌套 DOM 的组件上添加事件。 这是代码:

模板

<div class="bf-search-field">
  <input #productSearch
         [(ngModel)]="term"
         (ngModelChange)="search()"
         (blur)="closeAutocomplete()"
         (focus)="activeAutocomplete()"
         autocomplete="off" type="search" id="search"
         placeholder="Search black friday deals"
  />
  <button class="bf-search-field__search-btn"></button>
</div>
<div  class="bf-search-hints">
   <!--use for not duplicate full term in autocomplete-->
      <ng-container *ngFor="let product of products | async">
        <div *ngIf="(term !== product.title) && autocomplete" (click)="update(product.title)"
             class="bf-search-hint" >
          {{ product.title }}
        </div>
      </ng-container>
</div>

组件

/**
 * Created by lizarusi on 02.07.17.
 */
import {Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import { ProductService } from '../shared/product.service'
import {Product} from '../shared/product.model';

import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'product-search',
  templateUrl: './product-search.component.html',
  styleUrls: ['./product-search.component.scss'],
  providers: [ProductService]
})

export class ProductSearchComponent implements OnInit {

  @ViewChild('productSearch') searchField: ElementRef;
  products: Observable<Product[]>;
  autocomplete = true;
  term = '';
  private searchTerms = new Subject<string>();
  constructor(private productService: ProductService) {};
  search(): void {
    console.log('term ' + this.term);
    this.searchTerms.next(this.term);
  }
  ngOnInit(): void {
    this.products = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap( term => this.productService.searchProducts(term))
      .catch((err) => {
          console.log(err);
          return Observable.of<Product[]>([]);
    });
  }
  closeAutocomplete(): void {
    this.autocomplete = false;
  }
  activeAutocomplete(): void {
    this.autocomplete = true;
    this.search();
  }
  update(value: string): void {
    console.log('asaa');
    this.term = value;
    this.searchField.nativeElement.focus();
  }
}

在这种情况下,我的(点击)不起作用。我想它会发生 因为 *ngIf 从 DOM 中删除我的元素而不是再次创建它,但未分配事件侦听器。

问题是:如何在 *ngIf 内部/一起使用(单击)?或任何其他建议来解决这个问题。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    更新:

    我查看了 ngIf 和 ngFor 之外的代码,并意识到您试图在 ngFor 中直接使用 Observable,而不是订阅 Observable。一般的想法是,在观察数据之后,您需要将数据推送到正确格式的变量中。查看本指南了解更多信息:https://angular-2-training-book.rangle.io/handout/observables/using_observables.html

    特别是这部分代码:

      let subscription = this.data.subscribe(
          value => this.values.push(value),
          error => this.anyErrors = true,
          () => this.finished = true
      );
    

    在您的情况下,this.data 将是 this.products,而 this.values 将是一个新变量。如果您使用 this.finished,您可以将其替换为 ngIf 中的条件

    【讨论】:

    • 感谢您的回答!但不幸的是,它没有帮助:(
    • 你愿意创建一个 plunkr 吗?
    • 您可以使用它来尝试和复制:plnkr.co/edit/reBrvXwQ5z4ogl289rDk 这是一个工作示例。 3 秒后 ngIf 出现,5 秒后动态元素发生变化。两者都可以点击并写入控制台。
    • 谢谢!我尝试在 plunkr 中做同样的例子并且一切正常,所以我进入我的代码并意识到问题出在 (blur) 中,它在点击事件触发之前隐藏了下拉菜单。
    • “问题出在(模糊)中,它在点击事件触发之前隐藏了下拉菜单” - 结果这也是我的问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多