angular - Angular 2 - 检测绑定属性何时收到值
问题描述
我想知道保税财产何时收到一个值,即使它是相同的值。
例如
那是一个特征组件
import {
Component,
OnInit,
Input,
OnChanges,
SimpleChanges
} from '@angular/core';
@Component({
selector: 'feature-component',
templateUrl: './template.html',
styleUrls: ['./style.sass']
})
export class FeatureComponent implements OnInit, Onchanges {
@Input() bondedProperty: any;
ngOnInit() {
}
ngOnChanges(simpleChanges: SimpleChanges) {
// not called inside the setInterval function
console.log('the bonded property received any value.');
}
}
应用程序的组件
import {
Component,
AfterViewInit
} from '@angular/core';
@Component({
selector: 'app-component',
templateUrl: './template.html',
styleUrls: ['./style.sass']
})
export class AppComponent implements AfterViewInit {
bondedProperty: any;
constructor() {
this.bondedProperty = 10;
}
ngAfterViewInit() {
const
interval = setInterval(
() => {
this.bondedProperty = 10;
console.log('function called after interval');
clearInterval(interval);
}, 5000
);
}
}
最后,应用程序的模板
<feature-component
[bondedProperty]="bondedProperty"
>
</feature-component>
bondedProperty
ngOnChanges
问题是,如果没有调用相同的值,并且该ngDoCheck
方法不能解决我的问题,因为我不知道“更改”是否在bondedProperty
.
解决方案
据我所知,如果Angular 被设计为仅调用ngOnChanges
或值实际发生变化,则无法实现这一点。@Input setters
ngOnChanges
setter
如果您想检测新值,即使它们与以前的值相同,您真正想要的可能是检测某种事件。您可以将 RxJSBehaviorSubject
用于这种目的。
特征组件
import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'feature-component',
template: 'property: {{ bondedProperty$ | async }}',
styleUrls: ['./style.sass']
})
export class FeatureComponent implements OnInit, Onchanges {
@Input() bondedProperty$: BehaviorSubject<any>;
ngOnInit() {
this.bondedProperty$.subscribe(value =>
console.log('the bonded property received any value.')
);
}
}
应用组件
import { Component, AfterViewInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-component',
template: '<feature-component [bondedProperty$]="bondedProperty$"></feature-component>',
styleUrls: ['./style.sass']
})
export class AppComponent implements AfterViewInit {
bondedProperty$ = new BehaviorSubject<any>(0);
constructor() {
this.bondedProperty$.next(10);
}
ngAfterViewInit() {
const
interval = setInterval(
() => {
this.bondedProperty$.next(10);
console.log('function called after interval');
clearInterval(interval);
}, 5000
);
}
}
推荐阅读
- python - 我无法使用 xpath 或 CSS 类在 HTML 页面中定位元素
- c# - C# 发送推送通知 Firebase 云消息传递
- node.js - MongoDB 聚合 $group 阶段已从外部创建的值/变量
- python - BeautifulSoup 返回“无”对象类型
- excel - 网页硒VBA上的选择按钮
- html - Edge中自定义下拉箭头图标样式中的CSS线性渐变问题
- ruby-on-rails - AWS QuickSight rails 集成授权代码错误
- python - 如何在 Django 中创建一个用户模型,其中包含一个朋友列表,这些朋友也是“用户”模型
- wordpress - 自定义帖子类型短代码按 id 排序的问题
- php - 在多个文件夹上上传多个文件