首页 > 解决方案 > 观察变量变化 Angular

问题描述

如何从 React on Angular 执行这段代码?

let var;

//watch for var changes
useEffect(() => {
   console.log(var)
}, [var])

标签: angular

解决方案


在 Angular 中,我们使用双向数据绑定来实现这一目的。考虑到这一点,我们实际上并没有像 React 那样的“原生”状态观察者。

因此,要查看在组件类上声明的变量的所有更改,您必须使用插值对其进行包装,例如{{variable}}

您可以使用双向数据绑定添加<input>标签并添加[(ngModel)]指向组件类属性的指令和指令(ngModelChange)以在每次修改变量时执行一个函数。这是一个例子:

组件.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
 variable: string;

 execute() {
  console.log('Executed!');
 }
}

组件.html

<label for="interpolate">Interpolating:</label>
<input name="interpolate" id="interpolate" type="text" [(ngModel)]="variable" (ngModelChange)="execute()"/>
<h1>{{variable}}</h1>

要测试此示例,请不要忘记在您的以下位置添加FormsModule导入app.module.ts

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

推荐阅读