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

时间:2017-07-07 23:54:28

标签: javascript angular

我在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一起使用?或任何其他建议来解决这个问题。

1 个答案:

答案 0 :(得分: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

中的条件