Angular change a variable on component load

I have this configuration:

const routes: Routes = [
    { path: 'score', component: ScoreComponent }
];

when the component component loads, I want to change the value of the variable in the parent component.

The title variable is in the template of the parent component:

<div class="wrapper">
    <app-header></app-header>
    <app-menu [variablesForMenu]='variablesForMenu'></app-menu>
    <div class="content-wrapper">
        <section class="content-header">            
            <h1>
                {{title}}
            </h1>
        </section>
        <section class="content">
            <router-outlet></router-outlet>
        </section>
    </div>
</div>

How can i do this?

I would like to use EventEmitter, but I do not know how

+4
source share
1 answer

Three ways to do this:

  • Use a BehaviorSubject, subscribe to it in the parent element and call nextinit in the child element.

SomeService.service.ts

em: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

Parent.component.ts

variableToChange: any;
sub: Subscription;

constructor(someService: SomeService){}

ngOnInit() {
  sub.add(this.someService.em.subscribe(value => this.variableToChange = whatever));
}

Child.component.ts

constructor(someService: SomeService){}

ngOnInit() {
  this.someService.em.next(true);
}

  1. Pass the variable from parent to child as input, and then change this variable in child on init.

Parent.component.ts

variableToChange: any;

Parent.component.html

<child [variable]="variableToChange"></child>

Child.component.ts

@Input() variable: any;

ngOnInit() {
  this.variable = 'whatever';
}

  1. EventEmitter

Child.component.ts

@Output() em: EventEmitter<any> = new EventEmitter();

ngOnInit() {
  this.em.emit('something');
}

Parent.component.html

 <child (em)="setVariable($event)"></child>

Parent.component.ts

 variableToChange: any;

 setVariable(event) {
  this.variable = event; // event is emitted value
 }
+3

Source: https://habr.com/ru/post/1677005/


All Articles