ngOnChanges 不会记录表单更改



我正在从官方文档中学习ngOnChanges。它没有在HTML表单中记录更改。

我将FormsModuleReactiveFormsModule导入app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

我在app.component.html:中做了一个小表格

Favorite Color: <input type="text" [formControl]="favoriteColorControl">
<p>Your favorite color is {{favoriteColorControl.value}}.</p>

app.component.ts中,我导入了InputOnChangesSimpleChanges和表单模块。然后我创建了一个@Input对象,并设置ngOnChanges来记录更改:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnChanges {
@Input() favoriteColorControl = new FormControl('');
ngOnChanges(changes: SimpleChanges): void {
console.log(this.favoriteColorControl.value);
console.log(changes);
console.log(changes.favoriteColorControl.currentValue);
}
}

这种形式很管用。如果您键入";粉红色";进入形式,它告诉你最喜欢的粉红色。但控制台中没有任何日志。

我在某个地方读到ngOnChanges只检测从子组件传递到父组件的更改。我制作了一个子组件,并在父视图中显示了子视图,但没有记录任何内容。

你做得太不对了。反应式不使用@Input,因此不受ngOnChanges的约束。你声称你";跟随";教程,但里面并没有这样的东西。使用@Input是一回事,使用反应形式是另一回事。

当某些(当前(组件@Input绑定将更改时,ngOnChanges将激发。在您的情况下,您没有绑定任何东西(来自像<app-component [favoriteColorControl]="something">这样的组件外部(,所以它不会工作。

要收听无功控制的变化,请使用favoriteColorControl.valueChanges.subscribe(ctrlValue=>doSomethingWithIt)

最新更新