-1

I am working on a small web game using Angular 6. I have 2 relevant components, play.component and setup.component. The idea is that the user can choose things like difficulty in the setup-component and the user input changes the innerHTML of the elements in the play component. However I don't manage to come up with a way to save the user input in the setup component and access it afterwards from the play component.

I spent some time now looking for my problem and couldn't find anything. If you have alternatives to my solution, please tell me :)

Thanks

Code below

<div id="dropdown">
  <p-dropdown [options]="ai" [(ngModel)]="selectedAi" optionLabel="difficulty">
  </p-dropdown>
</div>
<div id="check">
  <p>Do you want to start? <p-checkbox [(ngModel)]="begin" binary="true">
    </p-checkbox>
  </p>
</div>

I want to access the variables selectedAI and begin from another component. How do I do it?

Walter Luszczyk
  • 1,369
  • 2
  • 19
  • 36

1 Answers1

2

Learn about Component Interaction. If you have Parent-child interaction relationship, you should be using

  • @Input decorator binds a property within one component (child component) to receive a value from another component (parent component). This is one-way communication from parent to child.

Example Source

<user-profile [user]="currentUser"></user-profile> // currentUser value of parent gets binded to user Input decorator

Then in the user-profile child component definition have @Input user to receive value from the parent.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'user-profile',
  template: '<div>{{user.name}}</div>'
})
export class UserProfile {
  @Input() user;
  constructor() {}
}
  • @Output decorator binds a property of a component to send data from one component (child component) to calling component (parent component). Thione-waye way communication from child to the parent component.

Example

import { Component, Input } from '@angular/core';

@Component({
  selector: 'user-profile',
  template: '<div>{{user.name}}</div>'
})
export class UserProfile {
  @Input() user;
  @Output() countChange: EventEmitter<number> = new EventEmitter<number>();
  constructor() {}
  clickChange() {
     this.countChange.emit(value);
  }

}

In the html component define

<user-profile [user]="currentUser" (countChange)="getCount($event)"></user-profile>

If data passing happens within components of the same level. angular.services need to be used.

Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45