Hey there! Take a look at this stackblitz link where I've refactored your code.
Before anything else, it's important to pass the control value to where you want it to be displayed.
app.component
<form [formGroup]="parentForm">
<app-common-dropdown [controlForDisplay]="parentForm.get('city')"
placeHolder="select district"
[dataList]="['bangalore','chennai','pune']"></app-common-dropdown>
<app-common-dropdown [controlForDisplay]="parentForm.get('state')"
placeHolder="select distance"
[dataList]="[100,200,300,400]"></app-common-dropdown>
<app-common-dropdown [controlForDisplay]="parentForm.get('country')"
placeHolder="select state"
[dataList]="['karnataka','tamil nadu','mumbai']"></app-common-dropdown>
</form>
<button type="submit" (click)="getFormValues()">submit</button>
I have added a new input to your app-common-dropdown
called controlForDisplay
to pass the reference of the desired formControl
to the component. I also removed the dropdownId
, the reason for this will be explained later.
common-dropdown.component.html
<div [ngClass]="{'cs-active': dropdownOpen}"
class="cs-select cs-skin-border"
tabindex="0">
<span (click)="selectClicked($event)" class="cs-placeholder">
{{!!controlForDisplay.value ? controlForDisplay.value : placeHolder }}
</span>
<div class="cs-options">
<ul>
<li *ngFor="let item of dataList" (click)="selectOption(item)">
<span>{{item}}</span></li>
</ul>
</div>
</div>
In the common-dropdown.component.html
, the key line is
{{!!controlForDisplay.value ? controlForDisplay.value : placeHolder }}
With the added controlForDisplay
input, we can access the reference of the formControl
that holds the default value of the dropdown. It will display the default value if present, otherwise it will show the placeholder.
commpon-dropdown.component.ts
@Component({
selector: 'app-common-dropdown',
templateUrl: './common-dropdown.component.html',
styleUrls: ['./common-dropdown.component.css']
})
export class CommonDropdownComponent {
@Input() placeHolder: string;
@Input() dataList: any;
@Input() controlForDisplay: FormControl = new FormControl()
dropdownOpen = false;
selectClicked(event: any) {
this.dropdownOpen = true
}
selectOption(value: string) {
this.controlForDisplay.patchValue(value)
this.closeDropDown('')
}
closeDropDown(event: any) {
this.dropdownOpen = false;
}
}
The main change here is using the formControl API with patchValue
instead of native elements to update the formControl value. This action updates the entire form accessible by both parent and current components.
p.s.
Don't forget to add the CommonModule
in your app.module.
This should resolve the issue. It's recommended to use Angular APIs over DOM APIs when building Angular web pages. Check out the official Angular tutorial Tour of Heroes for more guidance.