How to Call a Function When Element Is Loaded At Angular

How do I automatically run a function when the page is loaded?

ngOnInit() is the right place, when you want to call the method onload. If the data is async 'selected' can still be undefined when the template is rendered. To avoid the error you can wrap the block with a condition like @Flignats did or simply add a ? like

  <h1>{{selected?.title}}</h1>
{{selected?.person_id}}

The ?. stops evaluating when selected is null or undefined.

You are assigning the data outside the subscription. It should be like this:

getData(){
...
this.http.get(url).subscribe(data => {
this.data = data;
this.selected=this.data.find(item=>
{
if(item['person_id']===person_id)
{
return true;
}
return false;
});
console.log(person_id, this.selected);
});
}

Angular 9 call function when two components loaded

I think there is a simple solution.

@Output()
allLoaded = new EventEmitter();

oneLoaded = false;

ngAfterViewInit() {
this.emitAllLoaded();
}

yourFunctionWhereHttpClientGetLocated() {
this.http.get(..).subscribe(() => {
this.emitAllLoaded();
});
}

emitAllLoaded() {
if (oneLoaded) this.allLoaded.emit();
oneLoaded = true;
}

You might don't need to use Observable or Subject

How to call function when html is loaded in ngFor

Make a new component with code that look like this:

@Component({
selector: 'my-slider',
template: '<slider #mySlider></slider>'
})
export class MySlider {
@ViewChild('mySlider') slider: any; // can be ElementRef;

ngAfterViewInit() {
// slider is available
this.slider.slider();
let value = this.slider.attr("data-slider-value");
this.slider.slider('setValue', value);
}
}

Like I said in comment, I didn't test it but that's the good way for me.

You can find docs about lifecycle and child view here : http://learnangular2.com



Related Topics



Leave a reply



Submit