I have an angular autocomplete-tree component and I have an issue with the autocomplete panel width.
I have two requirements that I can solve individually but not together:
- The panel should grow once the content is wider than the panel. I used
[panelWidth] = "auto"
for this and it works perfectly. - The panel should have a minimum width of the host input. Can also use panelWidth for this but then I lose the functionality in the first point.
From Change the mat-autocomplete width?) I saw I can use [panelWidth] = "auto"
.
I know I can use the css styling
.mat-autocomplete-panel{min-width: "300px"}
but don't know how to get the width of the specific input.
So I resorted to javascript. I saw in the documentation that AutocompletePanel exposes the panel ElementRef, but this value seems to be undefined no matter what I do? Is the right way to acquire this value with @ViewChild
?
I have the following code that runs on the opened
event.
<mat-autocomplete #autocomplete (opened)="opened()" [panelWidth]="auto" #auto="matAutocomplete">
@ViewChild("auto") autocomplete: MatAutocomplete;
@ViewChild("autoTreeInput") autoTreeInput: ElementRef;
opened = () => {
setTimeout(()=>{
let p = this.autocomplete.panel?.nativeElement; //always null because panel is undefi
console.log("opened", p, this.autocomplete);
if (!p ) return
p.style.minWidth =
this.autoTreeInput.nativeElement.getBoundingClientRect().width + "px";
},1000)
};