I am trying to close the collapse
panel on click outside of the drop down. i try with following code :
import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';
declare var $:JQueryStatic;
import { State } from "./../../state/app.state";
import * as fromSetupConfig from "./../../setup-config/state/setup-config.reducer";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
constructor(private store:Store<State>) { }
currentName:string;
ngOnInit() {
this.store.pipe(select(fromSetupConfig.getCurrentName)).subscribe(newName => {
this.currentName = newName
});
$(document).click(function(e) {
if (!$(e.target).is('.panel-body')) {
$('.collapse').collapse('hide'); //throws error
}
});
}
}
But getting error as error: Property collapse does not exist on type
JQuery` - how to fix this?
The issue you're having here is because of the typescript compiler. To circumvent that, you could initialize the collapse and other elements in a basic JS file. You will need to import this file so create it either in the assets folder (and link it in your index.html
) or in another location and mention it in the scripts
part of your angular.json
.
To initialize collapse, the content of this JS file would be :
$(document).click(function(e) {
if (!$(e.target).is('.panel-body')) {
$('.collapse').collapse('hide'); //throws error
}
});
This would initialize all Jquery functions, when the document gets ready.
If you want to do that at a specific moment in the Angular flow, wrap the call in a function like so :
function collapse() {
$(document).click(function(e) {
if (!$(e.target).is('.panel-body')) {
$('.collapse').collapse('hide'); //throws error
}
});
}
To call it in a Typescript file, you'll need to first declare the function. For example, to initialize the jquery functions in ngOnInit()
:
declare function collapse();
ngOnInit() {
collapse();
}
This way you won't need to import 'bootstrap';
anywhere and so you won't break your other components.