Angular ngOnChanges方法

时间:2018-06-03 11:30:27

标签: angular

我是Angular的新手,最近我一直在研究LifeHooks的组件,而且我真的对ngOnChanges一无所知。它仅在子组件上触发吗? 如果我使用这样的代码: app.component.ts:

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [Logger]
})
export class AppComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, OnDestroy {
    title = 'Tour of Heroes';
    heroes = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
    myHero = this.heroes[0];
    hero: string;
    power: string;

模板tike:

<input [(ngModel)]="hero" placeholder="Hero name">
<input [(ngModel)]="power" placeholder="Hero power">

 <!--Using [] brackets can set property of COMPONENT or html ELEMENT-->
<app-on-changes [hero]="hero" [power]="power"></app-on-changes>

它触发了孩子的ngOnChanges方法但是当我在子模板中使用输入绑定时 - 该方法没有被调用。 上changes.component.html:

<p>
  <input [(ngModel)]="hero" placeholder="Hero name">
  <input [(ngModel)]="power" placeholder="Hero power">

  {{hero}}  {{power}}
</p>

上changes.component.ts:

@Component({
    selector: 'app-on-changes',
    templateUrl: './on-changes.component.html',
    styleUrls: ['./on-changes.component.css'],
    providers: [Logger]
})
export class OnChangesComponent implements OnInit, OnChanges {
    @Input() hero: string;
    @Input() power: string;
    constructor(private logger: Logger) {
    }

    ngOnInit() {
    }

    ngOnChanges(changes: SimpleChanges): void {
        this.logger.log('OnChangeComponent changed properties');

        for (let propName in changes) {
            let chng = changes[propName];
            let cur  = JSON.stringify(chng.currentValue);
            let prev = JSON.stringify(chng.previousValue);
            this.logger.log(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
        }
    }

}

1 个答案:

答案 0 :(得分:2)

当父组件修改(或初始化)绑定到子项的输入属性的值时,将调用ngOnChanges()。因此,如果组件没有父组件,则不会调用ngOnChanges()。

您正在使用双向绑定更改@Input属性的值,但这不会调用ngOnChanges()。