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
Regex to Replace Multiple Spaces With a Single Space
Jquery Get Select Option Value Empty
Exclude a Folder from Glob Pattern Matching
Javascript: Check If Page Is At the Top
Updating Value of Multidimensional Array of Object
Why Am I Getting an Expected an Assignment or Function Call and Instead Saw an Expression
Storing Object Inside a Variable from API JavaScript
Angular 4 - Cannot Read Property Status of Null While Displaying Validation Error
How to Convert Utf8 String to Byte Array
How to Loop Over Object Properties With Ngfor in Angular
Pull Variable Value from JavaScript Source Using Beautifulsoup4 Python
Chart.Js Draw Custom Grid Lines
How Does Group by Works in Sequelize
Why the Value of Input Elements Are Not Changing
How to Display JavaScript Datetime in 12 Hour Am/Pm Format