typescript - การเรียกใช้ฟังก์ชันหลังจาก DOM ของ Angular Component มีการเปลี่ยนแปลง คล้ายกับ ngAfterViewInit
ฉันมีคอมโพเนนต์ที่สร้างตัวชี้แนะจำนวนมากขึ้นอยู่กับอินพุต ในตัวอย่างด้านล่างนี้ (ไม่ใช่โค้ดจริง แต่ย่อมาให้สั้นที่สุดเท่าที่จะอธิบายคำถามได้) คอมโพเนนต์จะรับคอนฟิกเป็น Input() ใช้ MyService เพื่อแปลงเป็น this.fields และไดเร็กทีฟ dynamicField จะเรนเดอร์ฟิลด์จริง ๆ ในคอมโพเนนต์ หลังจากฟิลด์ทั้งหมดถูกเรนเดอร์โดยไดเร็กทีฟแล้ว ฉันต้องการให้ doSomething() ฉันได้ทำสิ่งนั้นโดยใช้ ngAfterViewInit() ซึ่งทำงานได้ดี
ตอนนี้ปัญหาคือ: ต่อไปฉันต้องการให้เกิดการเปลี่ยนแปลงของ this.fields เมื่อบางคอมโพเนนต์ถูกลบออกและคอมโพเนนต์อื่น ๆ ถูกเพิ่มเข้ามา แต่ฉันจะทำอย่างไรให้รัน doSomething() อีกครั้ง หลังจากที่ directive ทั้งหมดถูกแสดงผลอีกครั้ง? ngAfterViewinit() ไม่ถูกเรียกในกรณีนี้
import { MyService } from './myService.service';
@Component({
selector: 'mycomp',
template: '<ng-template *ngFor="let field of fields;" dynamicField [config]="field"></ngtemplate><button (click)="myTrigger()">Trigger</button>'
})
export class MyComponent implements AfterViewInit, OnInit{
@Input() config: object;
fields: object[];
constructor(myService: MyService){
}
ngOnInit(){
this.fields = this.myService.getFields(this.config);
}
myTrigger(){
this.fields.pop();
this.fields.push({'id': 'someotherfield', 'label':'someotherfield'})
}
doSomething() {
console.log('dosomething');
}
ngAfterViewInit(){
doSomething();
}
}
คำตอบ #1
การเลื่อนการดำเนินการจนถึงรอบถัดไปโดยใช้ setTimeout อาจใช้ได้:
myTrigger(){
this.fields.pop();
this.fields.push({'id': 'someotherfield', 'label':'someotherfield'})
setTimeout(() => {
this.doSomething()
})
}
คำตอบ #2
ลองอันนี้:
import { Component, AfterViewChecked, OnInit} from '@angular/core';
export class MyComponent implements AfterViewChecked, OnInit{
ngAfterViewChecked(){
doSomething();
}
}
