Consider using BehaviorSubject
in place of EventEmitter
. The main benefit is the ability to set an initial value. Check out this example:
https://stackblitz.com/edit/stackblitz-starters-bncmrb?file=src%2Fmain.ts
Main Application
@Component({
selector: 'app-root',
imports: [AppChild, AppChildTwo, AsyncPipe],
standalone: true,
templateUrl: './app.component.html',
})
export class App implements OnInit, AfterViewInit {
@Output()
// onGreetingChange: EventEmitter<string> = new EventEmitter();
onGreetingChange = new BehaviorSubject('Hola!!');
greetingTwo!: string;
constructor() {
// this.onGreetingChange.emit('Hola!!');
}
ngOnInit() {
// this.onGreetingChange.emit('Hola!!');
}
ngAfterViewInit() {
// this.onGreetingChange.emit('Hola');
}
}
HTML
<div><app-greeting [greeting]="onGreetingChange | async"></app-greeting></div>
<div>
<app-greeting-two (greetingTwo)="greetingTwo = $event"></app-greeting-two>
</div>
<h2>{{ greetingTwo }}</h2>
Child Component One
@Component({
selector: 'app-greeting',
standalone: true,
template: '<h1>{{ greeting }} Everyone!</h1>',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class AppChild {
@Input()
greeting!: string | null;
}
Child Component Two
@Component({
selector: 'app-greeting-two',
standalone: true,
template: '<h1>AppChildTwo: {{ greetingTwo | async }} Everyone!</h1>',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
imports: [AsyncPipe],
})
export class AppChildTwo {
@Output()
greetingTwo = new BehaviorSubject('Initial greeting TWO');
}