title: How do I automatically run a function when the page is loaded?
body: <p>I have a function called "getData" that needs to be executed in order to display certain information. I want it to run automatically but at the moment it only displays the data after clicking a button that activates the function - see (component.html): </p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;button (click)="getData()"&gt;Fetch Data&lt;/button&gt;
  </code></pre>
  
  <p>I already tried to insert the function in ngOnInit() in the component.ts-file:</p>
  
  <pre><code>ngOnInit(){
      this.getData()
    }
  </code></pre>
  
  <p>and tried onload in the component.html file: </p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;p onload="getData();"&gt;component works!&lt;/p&gt;
  </code></pre>
  
  <p>... both did not lead to the needed result</p>
  
  <p>This is how the code looks like (I basically get the data from an API Call and select an item with a certain id)
  component.ts</p>
  
  <pre><code>/*some code*/
  export class DetailComponent implements OnInit {
    public data: any = []
    public selected: any = []
    constructor(
      public http: HttpClient, 
      public route: ActivatedRoute) { }
  
    getData(){
      const person_id = this.route.snapshot.paramMap.get('person_id');
      const url ='http://localhost:4000/api/allpeople';
      this.http.get(url).subscribe(data =&gt; this.data = data);
      this.selected=this.data.find(item=&gt;
        {
          if(item['person_id']===person_id)
            {
              return true;
            }
          return false;
        });
      console.log(person_id, this.selected);
      return this.selected;
    }
  
    ngOnInit(){
      this.getData()
    }
  </code></pre>
  
  <p>component.html</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;h1&gt;{{selected.title}}&lt;/h1&gt;
  {{selected.person_id}}
  </code></pre>
  
  <p>When loading the page the console logs the following Error
  "Cannot read property 'title' of undefined" 
  and the error message refers to this line: <code>&lt;h1&gt;{{selected.title}}&lt;/h1&gt;</code></p>
  
  <p>But when I click the button it logs the data as it is supposed to. </p>
  
  <p>How can I let this automatically happen?</p>