Angular 12 access template place holder from child

Viewed 38

We have a root component that contains the base layout of a page. ie Header, foot, sidebar and main content

<main class="content">
        <router-outlet></router-outlet>
    </main>

Based on a route, we are looking for a way to push components into the side bar, possibly by using templates? ie, template place holder within the root component, and pass a template in using :-

<ng-template #sidepanel>
<div>here is the side panel content </div

tried to google, but only finding ways to pass from parent to child.

2 Answers

In this case, you can use a service to manage the state of the application. How can you do it? Create a service with a behavior subject

@Injectable({
  providedIn: 'root'
})
export class StateService {
  // I just create a subject for a string but you can create for eveything
  // that you want, primitives values string, number, object, custom object
  // arrays, etc
  readonly commentSubject: BehaviorSubject<string> = new BehaviorSubject('');
  readonly comment$ = this.commentSubject.asObservable();

  constructor() { }

  updateComment(value: string) {
    this.commentSubject.next(value);
  }
}

Then in your components you can update that comment by updated the subject

// component for route 1
export class OneComponent implements OnInit {
  constructor(private stateService: StateService) { }

  ngOnInit() {
    this.stateService.updateComment('New comment from one component');
  }
}

// component for route 2
export class SecondComponent implements OnInit {
  constructor(private stateService: StateService) { }

  ngOnInit() {
    this.stateService.updateComment('New comment from second component');
  }
}

After that you just need to subscribe inside of the side bar to that observable

export class SidebarComponent {
  comment$: Observable<string>;
  constructor(private stateService: StateService) {
    this.comment$ = this.stateService.comment$;
  }
}

//And in your HTML you can use async pipe to show the value of that observable
<p>Comment: {{ comment$ | async }}</p>

Related