I encountered a scenario where i need to do some processing of data on ngOnchanges(as the data is coming through @Input data bound property from parent component). During this transformation i need to use a property initialized in ngOnInit. I tried to use it directly but the value is coming as undefined. Can someone let me know how can i achieve this. Below is an example code for my scenario.
ParentComp HTML
<myParent [data]="list$ | async"></myParent>
ChildComp TS
export class {
@Input() data : any ; //data from parent
breakPoint$: Observable<number>
constructor(){}
ngOnInit(){
this.breakPoint$ = fromEvent(this.window, 'resize').pipe(
map(() => this.numOfCols())
);
}
ngOnChanges(changes: SimpleChanges) {
if (changes['data']) {
// need to do some data processing here based on numOfColumns value, so trying to access
this.breakPoint$.pipe(
) // Here i get cannot read property pipe of undefined error
);
numOfCols(): number {
return this.breakpointObserver.isMatched(`(max-width: 1008px)`) ? 4 : 5;
}
You can add another input propery and move numOfCols$ into the parent component.
ParentComp HTML
<myParent [data]="list$ | async"
[numOfCols]="numOfCols$ | async>
</myParent>
ParentCom TS
numOfCols$: Observable<number>;
constructor(private breakpointObserver: BreakpointObserver) {
this.numOfCols$ = breakpointObserver.observe('(max-width: 1008px)').pipe(
map(({matches}) => matches ? 4 : 5)
);
}
ChildComp TS
@Input() data: any;
@Input() numOfCols: number;
ngOnChanges(changes: SimpleChanges) {
if (changes['data']) {
// You can use this.numOfCols here
}
}