1

請問,請告訴我爲什麼ngOnChanges()函數沒有在angular2中觸發? 我試圖使用@Input更改message屬性,但onchange事件未被觸發。爲什麼ngOnChanges()函數未在角度2中觸發?

這裏是我的代碼 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'); 

    } 
} 
+0

實際上,它是**在我的控制檯中被解僱。究竟是什麼問題? – smnbbrv

+0

ngOnChanges僅在@Input參考發生更改時觸發 –

+0

它不會發射?這個messge不顯示onChange開除 – user944513

回答

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是從子組件中的事件。