小弟初学ng,摸索官网的例子,想请教下为何这个指令中的变量不能累加

就是控制台#号后面的数字(nextId)为啥不会累加,是因为指令每次调用都重新赋值了么;那文档的例子是如何实现的。

clipboard.png

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>
阅读 1.4k
1 个回答

页面上每个指令都是独立创建的,所以这部分代码

<div *ngFor="let hero of heroes" appSpy class="heroes">
  {{hero.id}}: {{hero.name}}
</div>

实际上是通过*ngFor创建了多个appSpy(SpyDirective),
对于每个SpyDirective指令来说,nextId都是独立的,能引起SpyDirective中nextId变化的情况只有在调用logIt()时(即ngOnInitngOnDestroy时),由于你这里指令生命周期经过了ngOnInit,并没有到ngOnDestroy,所以你SpyDirective中的nextId始终为1。
另外,感觉你可能是和SpyComponent中的nextId弄混了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏