Angular2 @ Input from async pipe - accessibility in ngOnInit

In one blog I read that:

The ngOnInit hook loop ensures that your bindings are easily accessible.

Is this also true with parameters passed using the async channel? For instance:

<myComponent [myInput]="myObservableVariable | async">
 ...
</myComponent>

Will the component wait for the variable to resolve before ngOnInit starts?

This would mean that sometimes when the data takes some time, loading the components can take a lot of time.

+4
source share
3 answers

The short answer is no, the component instance will not be delayed, and you will not get the resolved value in onInit if the observable was not resolved before the first change detection cycle.

Compare the following:

  // the value will be available in onInit
  obs = Observable.from([33]);

  // the value will not be available in onInit (you'll get null)
  obs = new Observable(observer => {
    setTimeout(() => {
      observer.next(33);
    }, 1000);

    setTimeout(() => {
      observer.complete();
    }, 3000);
  });


<child-component [inputproperty]="obs"><child-component>

async pipe:

async transform, . , . , null onInit.

, , , transform . , . onChanges.

+5

, , ( ). :

import { Component, Input, OnInit } from '@angular/core';

import { Observable } from 'rxjs/Rx';

@Component({
  selector: 'sub-component',
  template: `<p>{{ myInput }}</p>`,
})
export class SubComponent implements OnInit {
  @Input() myInput: string;

  ngOnInit() {
    console.log('initialised with', this.myInput);
  }
}

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello {{name}}</h1>
    <sub-component [myInput]="content$ | async"></sub-component>
  `
})
export class AppComponent { 
  name = 'Angular'; 
  content$ = Observable.of('Hello world').delay(5000);
}

https://plnkr.co/edit/jX7hOafuJtsWYhYrJx07?p=preview

initialised with null, .

, @Input , OnChanges.

+4

, , , : https://angular.io/guide/reactive-forms#when-to-set-form-model-values-ngonchanges

changeetection ( , async) Observable values, , onInit. , onChanges.

+1

Source: https://habr.com/ru/post/1677451/


All Articles