在组件中引用此自定义Angular 2指令(扩展NgFor),然后在页面上使用NgFor,会导致重复枚举:
import {
Directive,
ChangeDetectorRef,
IterableDiffers,
ViewContainerRef,
TemplateRef,
ElementRef
} from '@angular/core';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import { NgFor } from '@angular/common';
import { NgForRow } from './ngForRow';
import { AppComponent } from '../../app.component';
@Directive({
selector: '[ngTreeLeaf][ngTreeLeafOf]',
inputs: [
'ngTreeLeafOf',
'ngTreeLeafTemplate',
'ngTreeLeafRoute'
]
})
export class NgTreeLeaf extends NgFor {
private _routePattern: RegExp;
constructor(
viewContainer: ViewContainerRef,
templateRef: TemplateRef<NgForRow>,
iterableDiffers: IterableDiffers,
cdr: ChangeDetectorRef,
private _router: Router,
private _elementRef: ElementRef) {
super(viewContainer, templateRef, iterableDiffers, cdr);
}
set ngTreeLeafOf(leaves: Array<any>) {
this.ngForOf = leaves;
}
set ngTreeLeafRoute(route: string) {
this._routePattern = new RegExp(route + "\\b", "g");
}
set ngTreeLeafTemplate(value: TemplateRef<NgForRow>) {
this.ngForTemplate = value;
}
isLeafActive(urlString: string) {
if (!this._router || !this._routePattern) return false;
let active = this._routePattern.test(this._router.url);
if (active) {
this._elementRef.nativeElement.parentElement.classList.add("active");
}
else {
this._elementRef.nativeElement.parentElement.classList.remove("active");
}
return active;
}
}
正如this answer提到的那样,注释没有被继承,所以我不确定它在哪里获得了另外应用我的代码的动机。我假设它必须是与DI交互的父类名,或者是被发现的DoCheck和以某种方式共享的变量的组合。但我不能随便看到这个问题。
有什么建议吗?似乎here也好像我不会期待这个麻烦。