angular - 观察变量变化 Angular
问题描述
如何从 React on Angular 执行这段代码?
let var;
//watch for var changes
useEffect(() => {
console.log(var)
}, [var])
解决方案
在 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 { }
推荐阅读
- discord - 如何在 JDA 中重新启动机器人后恢复计时器
- parquet - 如何在 Impala 中显示复杂数据列(地图类型)中的所有字段?
- python - 在堆栈中查找特殊行的标准差
- javascript - 打字稿通用约束查找两种类型共享的属性名称
- hpc - Slurm - 如何将所有可用的 CPU 用于独立任务?
- c++ - 如何从时间复杂度为 n+mlgn 的 n 个已排序 *named* 向量中提取 m 个最小元素
- demandware - SFCC 为客户更改密码政策
- swift - Swift Realm:添加具有相同主键的新对象时如何处理错误?
- c# - C# OrderBy 和 ThenBy 的高级使用
- mkdocs - 如何阻止 material-mkdocs 修剪 inlineCodeBlock 空白?