How to access parent property in child controller - Angular 12

32 Views Asked by At

I have an Ionic 5 app (@ionic/angular 5.8.5), with Angular. I would like to get the value of comingFromOldBoardVol in the child controller.

Parent:

import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/services/api.service';
import { IBoard, IBoardData, ISorter } from 'src/app/model/profile';
import { ActivatedRoute, Router } from '@angular/router';
//import { Observable } from 'rxjs';
//import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-compare',
  templateUrl: './compare.page.html',
  styleUrls: ['./compare.page.scss'],
})
export class ComparePage implements OnInit {

  options: ISorter[] = [
    { code: ['timestamp', 'model'], title: 'recent_model', order: ['desc', 'asc'] },
    { code: ['gender'], title: 'gender', order: ['desc'] },
    { code: ['model'], title: 'model', order: ['desc'] },
    { code: ['win'], title: 'winning_board', order: ['desc'] }
  ];
  comingFromOldBoardVol: boolean;
  ....

Child:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { IBoard, IBoardData } from 'src/app/model/profile';
import { ApiService } from 'src/app/services/api.service';
import { WeightLevelService } from 'src/app/services/weightLevel.service';

@Component({
  selector: 'app-boards-tab',
  templateUrl: './boards-tab.page.html',
  styleUrls: ['./boards-tab.page.scss'],
})
export class BoardsTabPage implements OnInit {

  constructor(public api: ApiService, private router: Router, private service: WeightLevelService) { }
  //weighLevelService should be use uniquely in weightLevelPage, otherwise, rename the service

  async ngOnInit() {
  }

  openBoard(c: IBoard) {
    if (!this.parent.comingFromOldBoardVol) {
      this.router.navigate(['/boards/asSurfedBy', { brand: c.brand, model: c.model }]);
    } else {
      this.service.pickBoardForVolume(null);//don't do that in localStorage, do as in V1, pass a variable //pick board for volume means exactly nothing in the logics of my app. Makes no sense... the app is not understood. and that is why it still not working.
      this.router.navigate(['/volCompute', { id: c.id }]);
    }
  }

What can I try to resolve this?

1

There are 1 best solutions below

0
Jivopis On

As long as I understood the question correctly, you wan to pass variable from parent component to child. If it's correct, then you can use Input to pass value to child component. Example below:

Parent html:

...
<app-boards-tab [valueFromParent]="variableFromParent"></app-boards-tab>
...

Child component:

...
export class BoardsTabPage implements OnInit {
  @Input() valueFromParent: any;
  ...
}

Example with Angular 17, but techology is the same: https://stackblitz.com/edit/stackblitz-starters-arf8sp?file=src%2Fmain.ts