Angular Basics

MD
R
Markdown

Angular communication and patterns basics

Communication between Components via Service with Observables

// Service
public isUserLoggedIn = new Subject();
setUserLoggedIn(loggedIn: boolean) {
  this.isUserLoggedIn.next(loggedIn);
}

// Component A
constructor(private appService: AppService) { }
ngOnInit() {
  this.appService.isUserLoggedIn.subscribe((userLoggedIn: boolean) => {
    this.isUserLoggedIn = userLoggedIn;
  });
}

// Component B
constructor(private appService: AppService) { }
this.appService.setUserLoggedIn(false);

Communication using @ViewChild decorator

Parent component access the child component property via @ViewChild

<app-child #child></app-child>

@ViewChild('child') childComp: ChildComponent;

this.childComp.title = 'title coming from parent';

Projecting content

<app-welcome-message> <h2>Welcome to APP!</h2> </app-welcome-message>

<div>
  <ng-content></ng-content>
</div>

Created on 6/25/2019