【发布时间】: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