angular2监听变量

实现接口Docheck,检测页面上所有元素数据更新

import { Component, DoCheck } from "@angular/core";
export class LangListUserComponent implements DoCheck {

constructor(private differs: KeyValueDiffers) {
}
 
ngOnInit() {
 this.objDiffer = {};
 this.list.forEach((elt) => {
  this.objDiffer[elt] = this.differs.find(elt).create(null);
 });
}
 
ngDoCheck() {
 this.list.forEach(elt => {
  var objDiffer = this.objDiffer[elt];
  var objChanges = objDiffer.diff(elt);
  if (objChanges) {
   objChanges.forEachChangedItem((elt) => {
    if (elt.key === 'prop1') {
     this.doSomethingIfProp1Change();
    }
   });
  }
 });
}

formControl

module注入
import { FormsModule, ReactiveFormsModule } from ‘@angular/forms’;

组件中注入
import { FormControl } from ‘@angular/forms’;

可以订阅多次,相当于监听了多次:

import { Component, OnInit } from '@angular/core';
import { of } from "rxjs";
import { FormControl } from '@angular/forms';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    constructor() { }

    public col = new FormControl();
    public value: number = 22;
   
    ngOnInit() {
        this.col.valueChanges.subscribe(data => {
            console.log(data)
        });
        this.col.valueChanges.subscribe(data => {
            console.log(Math.random())
        });
    }
}

html

<input type="text" [formControl]="col" [(ngModel)]="value" />
发布了6 篇原创文章 · 获赞 1 · 访问量 809

猜你喜欢

转载自blog.csdn.net/ActiveXObject/article/details/105057989
今日推荐