I am trying to show Subtext in selectbox as shown in the screenshot below.

my .html code is:
<form [formGroup]="form">
<mat-select placeholder="country" [formControl]="country" >
<mat-select-trigger>
{{country.name}}
</mat-select-trigger>
<mat-option *ngFor="let country of countries" [value]="country">
{{country.name}}
<span class="example-additional-selection">
Staff ID: {{country.id}}
</span>
<span class="example-additional-selection">
Staff Name: {{country.firstname}}
</span>
<span class="example-additional-selection">
Staff Type: {{country.staff}}
</span>
</mat-option>
</mat-select>
</form>
my .ts code is:
@Component({
selector: 'select-custom-trigger-example',
templateUrl: 'select-custom-trigger-example.html',
styleUrls: ['select-custom-trigger-example.css'],
})
export class SelectCustomTriggerExample {
countries = [
{id: 1, name: "United States", staff: "Sales", firstname: "Mark"},
{id: 2, name: "Australia", staff: "Sales", firstname: "John"},
...
];
form: FormGroup;
constructor() {
this.form = new FormGroup({
country: new FormControl(null)
})
}
get country(): string {
return this.form ? this.form.get('country').value : '';
}
}
I am able to list the subtexts in the selectbox but I am unable to show the selected value.
When I put a static text inside the mat-select-trigger tags it works but when I put the variable {{country.name}} I get the following error
Error: Cannot read property 'name' of null
here is the stackblitz link: https://stackblitz.com/edit/angular-wd3vba-34arlh I would appreciate if you can have a look and tell me where I am doing wrong.
Thank you.
There error in your stackblitz
Error: Cannot find control with unspecified name attribute
is telling you that the control country cannot be found on the component. The code has a property getter that does not return a FormControl which is what the template is expecting. You have some options.
Update the getter to return a FormControl and not a string
get country(): FormControl {
return this.form.controls['country'] as FormControl;
}
Remove the getter and update the template to locate the control in the FormGroup
[formControl]="form.controls.country"
Remove the getter and create a direct reference to the FormControl on the component.
form: FormGroup;
country: FormControl;
constructor() {
this.country = new FormControl();
this.form = new FormGroup({
country: this.country,
});
}
To get the name use a safe navigation operator ?.
{{form.controls.country.value?.name}} - selected text goes here
Stackblitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With