鍍金池/ 問(wèn)答/HTML5  HTML/ 小弟初學(xué)ng,摸索官網(wǎng)的例子,想請(qǐng)教下為何這個(gè)指令中的變量不能累加

小弟初學(xué)ng,摸索官網(wǎng)的例子,想請(qǐng)教下為何這個(gè)指令中的變量不能累加

就是控制臺(tái)#號(hào)后面的數(shù)字(nextId)為啥不會(huì)累加,是因?yàn)橹噶蠲看握{(diào)用都重新賦值了么;那文檔的例子是如何實(shí)現(xiàn)的。

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>
回答
編輯回答
遲月

頁(yè)面上每個(gè)指令都是獨(dú)立創(chuàng)建的,所以這部分代碼

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

實(shí)際上是通過(guò)*ngFor創(chuàng)建了多個(gè)appSpy(SpyDirective),
對(duì)于每個(gè)SpyDirective指令來(lái)說(shuō),nextId都是獨(dú)立的,能引起SpyDirective中nextId變化的情況只有在調(diào)用logIt()時(shí)(即ngOnInitngOnDestroy時(shí)),由于你這里指令生命周期經(jīng)過(guò)了ngOnInit,并沒(méi)有到ngOnDestroy,所以你SpyDirective中的nextId始終為1。
另外,感覺(jué)你可能是和SpyComponent中的nextId弄混了

2017年4月14日 16:07