angular4 ngOnChanges方法

时间:2017-07-06 10:50:30

标签: angular

我已将angular1项目转换为angular4,但ngOnChanges方法似乎不起作用,我想在更改时看一些值

import {Component, OnInit, Input, OnChanges, SimpleChanges} from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'login-page',
    templateUrl: './login.page.html'
})

export class LoginPage implements OnChanges{

    userName: string = 'who am i';
    password: string;
    changeLog: string[] = [];

    ngOnChanges(changes: SimpleChanges) {
        console.info(changes);   //it didn't work anymore,please help me
        for (let propName in changes) {
            let chng = changes[propName];
            let cur  = JSON.stringify(chng.currentValue);
            let prev = JSON.stringify(chng.previousValue);
            this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
        }
    }
    showValue(f) {
        console.info(f);
    }
}

我已经尝试了所有方法使其对值变化敏感,我想为什么演示可以从angular.io(https://embed.plnkr.co/?show=preview)运行,但我的应用程序不起作用。我不知道如果我在我的应用中留下了一些重要的东西,那么ngOnChanges方法就不再起作用了

<ion-header>
    <ion-navbar>
        <ion-title>login</ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding>
    <form #f="ngForm" (ngSubmit)="showValue(f)">
        <ion-item>
            <ion-label fixed>username</ion-label>
            <ion-input type="text" required [(ngModel)]="userName" name="userName"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label fixed>username2</ion-label>
            <ion-input type="text" [value]="userName" (input)="userName = $event.target.value"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label fixed>pwd</ion-label>
            <input type="text" [(ngModel)]="password" name="pwd">
            <ion-input type="password" [(ngModel)]="password" name="pwd"></ion-input>
        </ion-item>
        <input ion-button type="submit" value="commit" class="button-block-ios button">
        <button ion-button outline>Primary Outline</button>
    </form>
    <div>
        <input type="text" [(ngModel)]="userName">
    </div>
    <div *ngFor="let chg of changeLog">{{chg}}</div>
    <div>{{userName}}</div>
    <!--<input type="text" class="item-input" [value]="userName" (click)=showValue>-->
</ion-content>

2 个答案:

答案 0 :(得分:2)

ngOnChanges()仅在更改检测更新组件的@Input()后通过角度更改检测调用,而不是在任意代码更改输入时。对于非输入的字段,永远不会调用ngOnChanges

你可以让你的字段得到getter / setter并在那里放置应该在更新值时执行的代码

_userName: string = 'who am i';
set userName(val:string) { this._userName = val; /* more code */}
get userName():string { return this._userName; }

答案 1 :(得分:1)

我建议您使用Reactive Forms

在这种情况下,您将能够:

constructor(fb: FormBuilder) {
    this.myForm = fb.group({
        'username': [
            '',                  // initial value
            Validators.required, // use if it's a required field
        ]
    });

    // subscribe on particular input change
    this.usernameControl = this.myForm.controls['username'];
    this.usernameControl.valueChanges.subscribe(() => {
        // use this.usernameControl.value
    });

    // or subscribe on any form input change
    this.myForm.valueChanges.subscribe(() => {
        // use this.myForm.value
    }); 

}

Html代码应包含:

<form>
    ...
    <input class="form-control" [formControl]="usernameControl">
    ...
</form>