我已经将我的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>发布于 2017-07-06 21:22:21
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; }发布于 2017-08-29 14:29:27
我建议您使用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>https://stackoverflow.com/questions/44946870
复制相似问题