Although adding another layer may seem more complicated, it’s much easier to deal with observables by dividing one component into two: the container component and the presentation component.
The container component deals only with observables, and not with representation. Data from any observables is passed to the view component through the @Input
properties and the async
pipe is used:
@Component({ selector: "recipe-container", template: `<recipe-component [recipe]="recipe$ | async"></recipe-component>` }) export class RecipeContainer { public recipe$: Observable<any>; constructor(private store: Store<AppState>) { this.recipe$ = store.select(recipeBuilderSelector); } }
The presented component receives simple properties and does not deal with observables:
@Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: "recipe-component", template: `...` }) export class RecipeComponent { public recipeForm: FormGroup; constructor(private formBuilder: FormBuilder) { this.recipeForm = this.formBuilder.group({ foodName: [""], description: [""] }); } @Input() set recipe(value: any) { this.recipeForm.patchValue({ foodName: value.name, description: value.description }); } }
The concept of using container and presentation components is a general Redux concept and is explained in presentation and container components .
source share