Skip to content

fix(autocomplete): update template when changing autocomplete in trigger #13814

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
25 changes: 17 additions & 8 deletions src/lib/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
NgZone,
OnDestroy,
Optional,
ViewContainerRef,
} from '@angular/core';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
Expand Down Expand Up @@ -117,7 +116,6 @@ export function getMatAutocompleteMissingPanelError(): Error {
})
export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
private _overlayRef: OverlayRef | null;
private _portal: TemplatePortal;
private _componentDestroyed = false;
private _autocompleteDisabled = false;
private _scrollStrategy: () => ScrollStrategy;
Expand All @@ -132,7 +130,7 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
private _manuallyFloatingLabel = false;

/** The subscription for closing actions (some are bound to document). */
private _closingActionsSubscription: Subscription;
private _closingActionsSubscription = Subscription.EMPTY;

/** Subscription to viewport size changes. */
private _viewportSubscription = Subscription.EMPTY;
Expand All @@ -144,6 +142,8 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
*/
private _canOpenOnNextFocus = true;

private _currentPortalAttached: TemplatePortal;

/** Stream of keyboard events that can close the panel. */
private readonly _closeKeyEventStream = new Subject<void>();

Expand Down Expand Up @@ -190,8 +190,8 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
this._autocompleteDisabled = coerceBooleanProperty(value);
}

constructor(private _element: ElementRef<HTMLInputElement>, private _overlay: Overlay,
private _viewContainerRef: ViewContainerRef,
constructor(private _element: ElementRef<HTMLInputElement>,
private _overlay: Overlay,
private _zone: NgZone,
private _changeDetectorRef: ChangeDetectorRef,
@Inject(MAT_AUTOCOMPLETE_SCROLL_STRATEGY) scrollStrategy: any,
Expand Down Expand Up @@ -570,7 +570,6 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
}

if (!this._overlayRef) {
this._portal = new TemplatePortal(this.autocomplete.template, this._viewContainerRef);
this._overlayRef = this._overlay.create(this._getOverlayConfig());

// Use the `keydownEvents` in order to take advantage of
Expand All @@ -596,9 +595,19 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
this._overlayRef.updateSize({width: this._getPanelWidth()});
}

if (this._overlayRef && !this._overlayRef.hasAttached()) {
this._overlayRef.attach(this._portal);
if (this._currentPortalAttached !== this.autocomplete._portal) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure why you'd need to do this. You can just call detach and then attach again to set the new portal.

Copy link
Contributor Author

@thomaspink thomaspink Oct 29, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@crisbeto I see your point there, but i am currently working on an issue (appears with and without this check) where a new panel will be created, even if the template has not changed. This especially happens in the tests, thats why a lot of them are failing.

For example take a look at this test: autocomplete.spec.ts#L267.
It is failing because we are creating a new panel on focusin and later on typeInElement (_attachOverlay gets called in multiple times).
So i need to find a way to check if we should detach/reatach (when a new mat-autocomplete has been set or not.
Maybe you have a good solution/idea for this one? Detach only if the template has changed?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't have to do it in _attachPortal though. Keeping _attachPortal as it is in master, aside from taking the portal from the panel, and calling detach when the autocomplete input changes should do it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed it to a detach in the autocomplete input. Thanks for your help

if (this._overlayRef.hasAttached()) {
// There might already be a portal attached, so detach first
this._overlayRef.detach();

// Need be unsubscribe of old portal subscriptions
this._closingActionsSubscription.unsubscribe();
}

this._overlayRef.attach(this.autocomplete._portal);
this._currentPortalAttached = this.autocomplete._portal;
this._closingActionsSubscription = this._subscribeToClosingActions();

}

const wasOpen = this.panelOpen;
Expand Down
50 changes: 50 additions & 0 deletions src/lib/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2221,6 +2221,38 @@ describe('MatAutocomplete', () => {
expect(formControl.value).toBe('Cal', 'Expected new value to be propagated to model');
}));

it('should work when dynamically changing the autocomplete', () => {
const fixture = createComponent(DynamicallyChangingAutocomplete);
fixture.detectChanges();
const input = fixture.debugElement.query(By.css('input')).nativeElement;

dispatchFakeEvent(input, 'focusin');
fixture.detectChanges();

expect(overlayContainerElement.textContent).toContain('First',
`Expected panel to display the option of the first autocomplete.`);
expect(overlayContainerElement.textContent).not.toContain('Second',
`Expected panel to not display the option of the second autocomplete.`);

// close overlay
dispatchFakeEvent(document, 'click');
fixture.detectChanges();

// Switch to second autocomplete
fixture.componentInstance.trigger.autocomplete = fixture.componentInstance.autoTow;
fixture.detectChanges();

// reopen agian
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agian -> again. Alternately these comments can be removed since they don't contribute much.

dispatchFakeEvent(input, 'focusin');
fixture.detectChanges();

expect(overlayContainerElement.textContent).not.toContain('First',
`Expected panel to not display the option of the first autocomplete.`);
expect(overlayContainerElement.textContent).toContain('Second',
`Expected panel to display the option of the second autocomplete.`);

});

});

@Component({
Expand Down Expand Up @@ -2607,3 +2639,21 @@ class AutocompleteWithNativeAutocompleteAttribute {
})
class InputWithoutAutocompleteAndDisabled {
}

@Component({
template: `
<input type="number" matInput [matAutocomplete]="autoOne">
<mat-autocomplete #autoOne>
<mat-option [value]="0">First</mat-option>
</mat-autocomplete>

<mat-autocomplete #autoTow>
<mat-option [value]="1">Second</mat-option>
</mat-autocomplete>
`,
})
class DynamicallyChangingAutocomplete {
@ViewChild('autoOne') autoOne: MatAutocomplete;
@ViewChild('autoTow') autoTow: MatAutocomplete;
@ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
}
13 changes: 12 additions & 1 deletion src/lib/autocomplete/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {
TemplateRef,
ViewChild,
ViewEncapsulation,
AfterViewInit,
ViewContainerRef,
} from '@angular/core';
import {
CanDisableRipple,
Expand All @@ -33,6 +35,7 @@ import {
MatOption,
mixinDisableRipple,
} from '@angular/material/core';
import {TemplatePortal} from '@angular/cdk/portal';


/**
Expand Down Expand Up @@ -92,14 +95,17 @@ export function MAT_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY(): MatAutocompleteDefau
]
})
export class MatAutocomplete extends _MatAutocompleteMixinBase implements AfterContentInit,
CanDisableRipple {
AfterViewInit, CanDisableRipple {

/** Manages active item in option list based on key events. */
_keyManager: ActiveDescendantKeyManager<MatOption>;

/** Whether the autocomplete panel should be visible, depending on option length. */
showPanel: boolean = false;

/** @docs-private */
_portal: TemplatePortal;

/** Whether the autocomplete panel is open. */
get isOpen(): boolean { return this._isOpen && this.showPanel; }
_isOpen: boolean = false;
Expand Down Expand Up @@ -165,12 +171,17 @@ export class MatAutocomplete extends _MatAutocompleteMixinBase implements AfterC
constructor(
private _changeDetectorRef: ChangeDetectorRef,
private _elementRef: ElementRef<HTMLElement>,
private _viewContainerRef: ViewContainerRef,
@Inject(MAT_AUTOCOMPLETE_DEFAULT_OPTIONS) defaults: MatAutocompleteDefaultOptions) {
super();

this._autoActiveFirstOption = !!defaults.autoActiveFirstOption;
}

ngAfterViewInit() {
this._portal = new TemplatePortal(this.template, this._viewContainerRef);
}

ngAfterContentInit() {
this._keyManager = new ActiveDescendantKeyManager<MatOption>(this.options).withWrap();
// Set the initial visibility state.
Expand Down