在AngularJS中,您可以使用$watch
的{{1}}函数指定观察者观察范围变量的变化。在Angular?
答案 0 :(得分:255)
在Angular 2中,更改检测是自动的...... $scope.$watch()
和$scope.$digest()
R.I.P。
不幸的是,开发指南的“更改检测”部分尚未编写(Architecture Overview页面底部附近有一个占位符,位于“其他内容”部分。)
以下是我对变更检测工作原理的理解:
setTimeout()
而不是$timeout
...因为setTimeout()
是猴子修补的。ChangeDetectorRef
来访问此对象。)当Angular创建组件时,会创建这些更改检测器。它们会跟踪所有绑定的状态,以便进行脏检查。从某种意义上说,这些与Angular 1为$watches()
模板绑定设置的自动{{}}
类似。onPush
更改检测策略),树中的每个组件都会检查一次(TTL = 1)...从顶部开始,深度优先订购。 (好吧,如果你处于开发模式,更改检测会运行两次(TTL = 2)。有关详细信息,请参阅ApplicationRef.tick()。)它使用这些更改检测器对象对所有绑定执行脏检查。
ngOnChanges()
以通知更改。 了解更多内容的其他参考资料:
ngDoCheck()
。答案 1 :(得分:85)
此行为现在是组件生命周期的一部分。
组件可以在OnChanges界面中实现ngOnChanges方法,以获取对输入更改的访问权限。
示例:
import {Component, Input, OnChanges} from 'angular2/core';
@Component({
selector: 'hero-comp',
templateUrl: 'app/components/hero-comp/hero-comp.html',
styleUrls: ['app/components/hero-comp/hero-comp.css'],
providers: [],
directives: [],
pipes: [],
inputs:['hero', 'real']
})
export class HeroComp implements OnChanges{
@Input() hero:Hero;
@Input() real:string;
constructor() {
}
ngOnChanges(changes) {
console.log(changes);
}
}
答案 2 :(得分:63)
如果除了自动双向绑定之外,您希望在值更改时调用函数,则可以将双向绑定快捷方式语法分解为更详细的版本。
<input [(ngModel)]="yourVar"></input>
是
的简写 <input [ngModel]="yourVar" (ngModelChange)="yourVar=$event"></input>
(参见例如http://victorsavkin.com/post/119943127151/angular-2-template-syntax)
你可以这样做:
<input [(ngModel)]="yourVar" (ngModelChange)="changedExtraHandler($event)"></input>
答案 3 :(得分:16)
您可以使用getter function
或get accessor
作为角度2的监视。
请参阅演示here。
import {Component} from 'angular2/core';
@Component({
// Declare the tag name in index.html to where the component attaches
selector: 'hello-world',
// Location of the template for this component
template: `
<button (click)="OnPushArray1()">Push 1</button>
<div>
I'm array 1 {{ array1 | json }}
</div>
<button (click)="OnPushArray2()">Push 2</button>
<div>
I'm array 2 {{ array2 | json }}
</div>
I'm concatenated {{ concatenatedArray | json }}
<div>
I'm length of two arrays {{ arrayLength | json }}
</div>`
})
export class HelloWorld {
array1: any[] = [];
array2: any[] = [];
get concatenatedArray(): any[] {
return this.array1.concat(this.array2);
}
get arrayLength(): number {
return this.concatenatedArray.length;
}
OnPushArray1() {
this.array1.push(this.array1.length);
}
OnPushArray2() {
this.array2.push(this.array2.length);
}
}
答案 4 :(得分:11)
这是另一种使用模型的getter和setter函数的方法。
@Component({
selector: 'input-language',
template: `
…
<input
type="text"
placeholder="Language"
[(ngModel)]="query"
/>
`,
})
export class InputLanguageComponent {
set query(value) {
this._query = value;
console.log('query set to :', value)
}
get query() {
return this._query;
}
}
答案 5 :(得分:5)
如果你想使它成双向绑定,你可以使用[(yourVar)]
,但是你必须实现yourVarChange
事件并在每次变量变化时调用它。
跟踪英雄变化的事情
@Output() heroChange = new EventEmitter();
然后当你的英雄变了,请拨打this.heroChange.emit(this.hero);
[(hero)]
绑定将为您完成剩下的工作
见示例:
答案 6 :(得分:3)
当您的应用仍然要求$parse
,$eval
,$watch
喜欢Angular中的行为
答案 7 :(得分:0)
这不能直接回答问题,但是我在不同情况下都会遇到这个Stack Overflow问题,以解决在angularJs中使用$ watch的问题。我最终使用了不同于当前答案中所述的另一种方法,并希望共享它,以防有人发现它有用。
我用来实现类似$watch
的技术是在Angular服务中使用BehaviorSubject
(more on the topic here),然后让我的组件订阅以获取(观看) 变化。这与angularJs中的$watch
类似,但需要更多的设置和理解。
在我的组件中:
export class HelloComponent {
name: string;
// inject our service, which holds the object we want to watch.
constructor(private helloService: HelloService){
// Here I am "watching" for changes by subscribing
this.helloService.getGreeting().subscribe( greeting => {
this.name = greeting.value;
});
}
}
为我服务
export class HelloService {
private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
constructor(){}
// similar to using $watch, in order to get updates of our object
getGreeting(): Observable<{value:string}> {
return this.helloSubject;
}
// Each time this method is called, each subscriber will receive the updated greeting.
setGreeting(greeting: string) {
this.helloSubject.next({value: greeting});
}
}
这是Stackblitz上的演示