要在Angular中监控变化时注入NgControl,可以使用ngOnChanges生命周期钩子来实现。下面是一个示例代码:
首先,在组件中导入需要的模块和服务:
import { Component, OnInit, OnChanges, SimpleChanges, ViewChild } from '@angular/core';
import { NgControl } from '@angular/forms';
然后,在组件类中实现OnChanges接口,并在类中注入NgControl:
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent implements OnInit, OnChanges {
@ViewChild(NgControl) ngControl: NgControl;
constructor() {}
ngOnInit() {}
ngOnChanges(changes: SimpleChanges) {
if (changes.ngControl) {
console.log('NgControl changed:', this.ngControl);
// 进行其他操作
}
}
}
在ngOnChanges方法中,我们可以访问ngControl属性,并在其发生变化时进行相应的操作。