0

I have 2 components: HomeComponent and UserComponent.

home.component.ts :

    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent implements OnInit {

      constructor(private router: Router) { }
      users =  ['User1', 'User2', 'User3']
      selectedVal = ''

      ngOnInit() {
      }
      onChange(newValue) {
        this.selectedVal = newValue 
      }
    }

home.component.html :

<select class="custom-select custom-select-lg mb-3 content" [(ngModel)]="selectedVal" (ngModelChange)="onChange($event)" >

       <option [value]="i" *ngFor="let i of users"> {{i}}  </option>
    </select>
     <h1> Selected value is : {{selectedVal}} </h1>

When a value is selected in the list, I want to send the variable selectedVal from HomeComponent to UserComponent.

I'm trying to learn Angular, how can I do this ?

David Walschots
  • 12,279
  • 5
  • 36
  • 59
Develo55
  • 33
  • 4
  • 1
    If you are learning Angular, then read their documentation before asking something on Stack. https://angular.io/guide/component-interaction –  Mar 22 '18 at 10:48
  • 1
    I'm voting to close this question as off-topic because [there is documentation for that](https://angular.io/guide/component-interaction) –  Mar 22 '18 at 10:49
  • Please do not use the [tag:angularjs] tag for questions about [tag:angular]. – David Walschots Mar 22 '18 at 10:50
  • Please make an effort to search SO, there are plenty of questions and answers regarding this ;) – AT82 Mar 22 '18 at 11:32

1 Answers1

1

If HomeComponet and UserComponent are not in a parent-child relation, you should use a communication service between them.

You create a service, then you can inject it into both of the classes. That way, the data will be stored in the service.

If you need to see the update event, then you can have the value emitted via EventEmitter.

Check out the documentation on how to implement these.

ForestG
  • 17,538
  • 14
  • 52
  • 86
  • Thank you for your helpful and clear response. I developed a shared service and now I can display the selectedItem sent by HomeComponet in UserComponent. But when I refresh the page, the selectedItem disappears :( – Develo55 Mar 22 '18 at 14:26
  • If I understand correctly: If you want to have a permament selection, you should persist it. Presing F5 will reload your whole application. You should use a backing middleware which will persist your data to a Database. And when your app loads, you should check for stored selections there first. – ForestG Mar 23 '18 at 11:06