简体   繁体   English

Angular2(v4.2.5)click事件在* ngIF内部不起作用

[英]Angular2(v4.2.5) click event doesn't work inside *ngIF

I have the following problem in Angular: as I understand, *ngIf directive doesn't allow me to add event on nesting DOM's component. 我在Angular中遇到以下问题:据我了解,* ngIf指令不允许我在嵌套DOM的组件上添加事件。 This is the code: 这是代码:

Template 模板

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

Component 零件

/**
 * 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();
  }
}

In this case my (click) doesn't work. 在这种情况下,我的(点击)不起作用。 I suppose that it happens because *ngIf removing my element from DOM and than creating it again, but event listeners wasn't assigned. 我想发生这种情况是因为* ngIf从DOM中删除了我的元素,而不是再次创建它,但是未分配事件侦听器。

The question is: How can I use (click) inside/together with *ngIf? 问题是:如何在* ngIf内部/一起使用(单击)? Or any other suggestions to figured this out. 或解决此问题的任何其他建议。

Update: 更新:

I looked through your code beyond the ngIf and ngFor and realized you were attempting to directly use your Observable in your ngFor instead of a Subscription to the Observable. 我查看了ngIf和ngFor之外的代码,发现您正在尝试直接在ngFor中使用Observable而不是Subservable到Observable。 The general idea is that after you observe your data you'll want to then push the data into a variable of the proper format. 通常的想法是,在观察数据之后,您需要将数据推送到适当格式的变量中。 Check out this guide for more information: https://angular-2-training-book.rangle.io/handout/observables/using_observables.html 查阅本指南以获取更多信息: https : //angular-2-training-book.rangle.io/handout/observables/using_observables.html

And specifically this part of the code: 特别是这部分代码:

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

In your case this.data will be this.products, and this.values will be a new variable. 在您的情况下,this.data将是this.products,而this.values将是新变量。 If you use this.finished, you can replace that as your conditional in the ngIf 如果使用this.finished,则可以将其替换为ngIf中的条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM