I have a unique feature in my component that creates multiple directives based on user input. The simplified example below demonstrates how the component receives configuration data through an Input()
, processes it using a service called MyService
to generate this.fields
, and then uses the dynamicField
directive to display the fields within the component.
After all the fields are generated by the directive, I need to execute doSomething()
. I achieved this by utilizing ngAfterViewInit()
, which functions effectively.
However, I encounter a challenge: at a later stage, I wish to update this.fields
as some components are removed and new ones are added dynamically. How can I re-run doSomething() after all the directives have been re-rendered? In such cases, ngAfterViewinit()
fails to trigger.
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();
}
}