To transfer data from the body
component to the app
component, you must implement event binding using Output() and EventEmitter().
The necessary modifications should be made in the following files:
body.component.ts:
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-body',
templateUrl: './body.component.html',
styleUrls: ['./body.component.css']
})
export class BodyComponent implements OnInit {
@Output() valueChange = new EventEmitter()
constructor() { }
ngOnInit() {
}
changeVal(val){
this.valueChange.emit(val);
}
}
Add [(ngModel)]='selectedCountry'
in the app component HTML to monitor dropdown changes as shown below,
app.component.html:
<p>
App Component:
</p>
<select name="selectedCountry" [(ngModel)]='selectedCountry' class="rounded-inputs20 select-select col-md-3" (change)="onChange($event.target.value)">
<option *ngFor="let country of countries; let i = index" [value]="country.id">
{{country.name}}</option>
</select>
<app-body (valueChange)="getValueChange($event)"></app-body>
In the code above,
(valueChange)="getValueChange($event)"
is where you retrieve the data from the clicked button.
Subsequently, in the app component TypeScript file, you can create a function to handle the button click changes from the body component and update the dropdown selection by assigning the value of
this.selectedCountry = selectedOption.id
,
getValueChange(val) {
const selectedOption = this.countries.find(x => x.name == val);
this.selectedCountry = selectedOption.id;
this.onChange(selectedOption);
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular 5';
cities = {};
countries = [{
id: 1, name: 'France'
},
{
id: 2, name: 'Germany'
},
{
id: 3, name: 'Italy'
},
];
selectedCountry: any = this.countries[0].id;
ngOnInit() {
this.cities = this.countries.filter(x => x.id == 1);
}
onChange(deviceValue) {
this.cities = this.countries.filter(x => x.id == deviceValue);
console.log('onchange ', deviceValue)
}
getValueChange(val) {
const selectedOption = this.countries.find(x => x.name == val);
this.selectedCountry = selectedOption.id;
this.onChange(selectedOption);
}
}
Forked Stackblitz:
https://stackblitz.com/edit/angular-dropdown-65tfxg