I try to modify the code that uses depreciated class DynamicComponentLoader in Angular 2.
@Injectable()
export class ToastsManager {
container: ComponentRef<any>;
private options = {
autoDismiss: true,
toastLife: 3000
};
private index = 0;
constructor(private loader: DynamicComponentLoader,
private appRef: ApplicationRef,
@Optional() @Inject(ToastOptions) options) {
if (options) {
Object.assign(this.options, options);
}
}
show(toast: Toast) {
if (!this.container) {
// a hack to get app element in shadow dom
let appElement: ViewContainerRef = new ViewContainerRef_(this.appRef['_rootComponents'][0]._hostElement);
let bindings = ReflectiveInjector.resolve([
provide(ToastOptions, { useValue: <ToastOptions>this.options })
]);
this.loader.loadNextToLocation(ToastContainer, appElement, bindings)
.then((ref) => {
this.container = ref;
this.setupToast(toast);
});
} else {
this.setupToast(toast);
}
}
I cannot get it to work, I try to add ComponentRef in the constructor, but it does not work:
this.resolver.resolveComponent(this.type)
.then((factory: ComponentFactory) => {
this.container = this.container.createComponent(factory);
this.setupToast(toast);
});
} else {
this.setupToast(toast);
}
I try like this:
@Injectable()
export class ToastsManager {
@ViewChild('target', {read: ToastContainer}) target;
container: ComponentRef;
private options = {
autoDismiss: true,
toastLife: 3000
};
private index = 0;
constructor(private loader: DynamicComponentLoader, private resolver: ComponentResolver, private viewContainerRef
private appRef: ApplicationRef,
@Optional() @Inject(ToastOptions) options) {
if (options) {
Object.assign(this.options, options);
}
}
show(toast: Toast) {
if (!this.container) {
// a hack to get app element in shadow dom
let appElement: ViewContainerRef = new ViewContainerRef_(this.appRef['_rootComponents'][0]._hostElement);
let bindings = ReflectiveInjector.resolve([
provide(ToastOptions, { useValue: <ToastOptions>this.options })
]);
let self = this;
this.resolver.resolveComponent(this.type)
.then((factory: ComponentFactory<any>) => {
self.container = this.target.createComponent(factory);
this.setupToast(toast);
});
} else {
this.setupToast(toast);
}
}
It does not work.