就是控制台#号后面的数字(nextId
)为啥不会累加,是因为指令每次调用都重新赋值了么;那文档的例子是如何实现的。
spy.directive.ts
///<reference path="../../node_modules/@angular/core/src/metadata/directives.d.ts"/>
import {Directive, NgModule, OnDestroy, OnInit} from '@angular/core';
import {LoggerService} from './logger.service';
@Directive({selector: '[appSpy]'})
export class SpyDirective implements OnInit, OnDestroy {
private nextId: number;
constructor(private logger: LoggerService) {
this.nextId = 1;
}
ngOnInit() {
this.logIt(`onInit`);
}
ngOnDestroy() {
this.logIt(`onDestroy`);
}
private logIt(msg: string) {
this.logger.log(`Spy #${this.nextId++} ${msg}`);
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SpyComponent } from './spy.component';
import { LoggerService } from './logger.service';
import { SpyDirective } from './spy.directive';
@NgModule({
declarations: [
AppComponent,
SpyComponent,
SpyDirective
],
imports: [
BrowserModule,
FormsModule
],
providers: [
LoggerService
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
spy.component.ts
import {Component} from '@angular/core';
import {OnInit} from '@angular/core';
import {Hero} from './hero';
@Component({
selector: 'app-spy',
templateUrl: './spy.component.html'
})
export class SpyComponent implements OnInit {
heroes: Hero[] = [];
nextId: number;
name: string;
constructor() {
this.nextId = 1;
}
ngOnInit() {}
addHero() {
const h = new Hero(this.nextId++, this.name);
this.heroes.push(h);
}
removeHero() {
this.heroes.splice(this.heroes.length - 1, 1);
}
resetHero() {
this.heroes.splice(0, this.heroes.length);
}
}
spy.component.html
<input type="text" [(ngModel)]="name" />
<button type="button" (click)="addHero()">add</button>
<button type="button" (click)="removeHero()">remove</button>
<button type="button" (click)="resetHero()">reset</button>
<div *ngFor="let hero of heroes" appSpy class="heroes">
{{hero.id}}: {{hero.name}}
</div>
页面上每个指令都是独立创建的,所以这部分代码
实际上是通过
*ngFor
创建了多个appSpy(SpyDirective
),对于每个
SpyDirective
指令来说,nextId都是独立的,能引起SpyDirective
中nextId变化的情况只有在调用logIt()时(即ngOnInit
和ngOnDestroy
时),由于你这里指令生命周期经过了ngOnInit
,并没有到ngOnDestroy
,所以你SpyDirective
中的nextId始终为1。另外,感觉你可能是和
SpyComponent
中的nextId弄混了