Seven On the way
Seven On the way

Reputation: 5

angular4 ngOnChanges method

I have transformed my angular1 project to angular4 ,but ngOnChanges method seems not work ,I want to watch some values when they changed

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);
    }
}

I have try all the ways to make it sensitive to the value changes,I wander why the demo could run from angular.io(https://embed.plnkr.co/?show=preview) , but my app isn't work.I don't know if I had left some important things in my app, the ngOnChanges method didn't work anymore

<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>

Upvotes: 0

Views: 3402

Answers (2)

marbug
marbug

Reputation: 350

I would suggest you to use Reactive Forms

In such a case you'll be able to:

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 code should contain:

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

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

ngOnChanges() is only called by Angular change detection after change detection updates an @Input() of a component, not when arbitrary code changes an input. For fields that are not inputs, ngOnChanges is never called.

You can just make your fields getters/setters and put code there that should be executed when the value is updated

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

Upvotes: 2

Related Questions