为什么ngOnChanges()函数没有在角度2中触发?

时间:2017-02-13 09:52:45

标签: javascript angularjs angular angular2-routing angular2-template

请你告诉我为什么在{2}中没有触发ngOnChanges()函数? 我尝试使用message更改@Input属性,但不会触发onchange事件。

这是我的代码 https://plnkr.co/edit/BOw5vazUUM8WNh9C1CNa?p=preview

export class Test implements OnInit,OnChanges{
  name:string;
  @Input() message;
  constructor() {
    console.log('==constructor==')
    this.name = 'Angular2'
  }
  ngOnInit(){
     // this.myService.someMethod() 
       console.log('==ngOnInit==')
   }

    ngOnChanges() {
        console.log('onChange fired');

    }
}

1 个答案:

答案 0 :(得分:0)

我想你想在父母和孩子之间绑定数据,当孩子改变message时,父母将收到更新的值。

这是演示:

<强> app.ts

//our root app component
import {Component, NgModule,OnInit,OnChanges} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import {Test} from './test';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}} from parent</h2>
      <test [(message)]="name"></test>
    </div>
  `,
})
export class App implements OnInit,OnChanges{
  name:string;
  constructor() {
    console.log('==constructor==')
    this.name = 'Angular2'
  }
  ngOnInit(){
     // this.myService.someMethod() 
       console.log('==ngOnInit==')
   }

    ngOnChanges() {
        console.log('onChange fired');

    }
}

@NgModule({
  imports: [ BrowserModule,FormsModule  ],
  declarations: [ App ,Test],
  bootstrap: [ App ]
})
export class AppModule {}

<强> test.ts

import { Component, NgModule,OnInit,OnChanges,Input, Output, EventEmitter } from '@angular/core'

@Component({
  selector: 'test',
  template: `
    <div>
     {{message}}
     <input type="text" [ngModel]= "message" (ngModelChange)="onModelChange($event)"/>
    </div>
  `,
})
export class Test implements OnInit,OnChanges{
  name:string;
  @Input() message;

  @Output() messageChange = new EventEmitter('');
  constructor() {
    console.log('==constructor==')
    this.name = 'Angular2'
  }
  ngOnInit(){
     // this.myService.someMethod() 
       console.log('==ngOnInit==')
   }

    ngOnChanges() {
        console.log('onChange fired');

    }
  onModelChange(event) {
    this.message = event;

    this.messageChange.emit(this.message);
  }
}

演示:https://plnkr.co/edit/nU9Qkuf7bwgSga7Ce2Wc?p=preview

这是Angular中的自定义双向绑定。

<test [(message)]="name"></test>

当量:

<test [message]="name"(messageChange)="message = $event"></test>

其中messageChange是来自子组件的事件。