I want to have a preselected option on my dropdown list. i set to preSelectedLegalType the value on ngOnInit but i can't display it.How can i display this value?
My ts file
export class BusinessDetailsComponent implements OnInit{
legalTypes: any = ["Α.A.", "B.B, "C.C", "D.D.", "Ε.Ε"];
preSelectedLegalType: string = this.stateService.legalEntity.LegalType;
constructor(private stateService: StateService){
this.businessDetailsForm = this.createForm();
}
ngOnInit() {
this.businessDetailsForm.controls['legalType'].setValue(this.preSelectedLegalType, {onlySelf: true});
}
createForm() {
return this.fb.group({
legalType: [this.preSelectedLegalType, [Validators.required]],
businessName: ['', {validators: [Validators.required]}]
})
}
html
<select class="form-control custom-select-text" id="legalType" formControlName="legalType" required>
<option *ngFor="let legalType of legalTypes" [ngValue]="legalType" class="testhover" >{{legalType}}</option>
</select>
Use FormBuilder control()
method to create controls in the Form as shown below.
createForm() {
return this.fb.group({
legalType: this.fb.control(this.preSelectedLegalType, [Validators.required]),
businessName: this.fb.control('', [Validators.required])
});
}
The first argument of control()
method takes the initial value, followed by the array of Validators.
More about the control()
of FormBuilder can be found here . You can find the complete example here in Stackblitz.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.