Can i send a variable from index.html to app.component.ts
i have this script in index.html and i want to send url which is variable before removing query params to app.component.ts
<script type="text/javascript">
var url = window.location.toString();
if(url.indexOf("?") > 0) {
var sanitizedUrl = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, sanitizedUrl);
}
</script>
Of course you can. I made a small demo to show you how.
All you have to do is wrap your code as you did in index.html.
You have to declare the variable. You can do it inside the component as
import { Component } from '#angular/core';
// notice that foo is inited in index.html
declare var foo;
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
or in typings.d.ts. I recommend declaring it in typings.d.ts. If you're using angular-cli, and i assume, it is located in src/app/typings.d.ts.
declare var foo: any;
And that's it. You can use your variable anywhere in the app.
Inside .html file -->
<script>
const baseUrl = "http://0.0.0.0/";
</script>
in .ts file just declare the variable and use it -->
declare var baseUrl;
export const BASE_URL = baseUrl;
Related
Angular 4 supports below syntax
var HelloComponent = ng.core
Component({
selector: 'hello-cmp',
template: 'Hello World!',
viewProviders: [Service]
.Class({
constructor: [Service, function (service) {
},`
});
In Angular 5 , Class is missing anyone can provide Angular 5 with ES5 syntax currently
i am not able to switch ES6 so please avoid that suggestion.
if switching to ES6 is the only way then i will stick to angular 4 as of now
You need to use static properties annotations and parameters on your component class function something like this:
function Service() {}
function AppComponent(service) {
console.log(service);
}
AppComponent.prototype.ngOnInit = function() {
console.log('test ngOnInit');
};
AppComponent.annotations = [
new Component({
selector: 'my-app',
template: '<h1>Example of Angular 5.0.5 in ES5</h1>',
viewProviders: [Service]
})
];
AppComponent.parameters = [ Service ];
Plunker Example
I would like to separate the service from the controller in my angularjs application, I did it in a following way:
the app.js there is:
var myApp = angular.module('myApp',['restangular','ui.router','myApp.controllers','myApp.services']);
the controllers.js:
angular.module('myApp.controllers',[]);
the services.js:
angular.module('myApp.services',[]);
I have a controllers related to the controllers.js:
angular.module('myApp.controllers',[]).controller('ContactController', ContactController);
ContactController.$inject = [ '$scope', 'ContactService' ];
function ContactController($scope, ContactService) {
console.log("here call ctrl contact");
$scope.contacts = ContactService.getAll();
}
This ContactController call the service ContactService defined in a separate file:
ContactService .js
angular.module('myApp.services',[])
.factory('ContactService', function(Restangular){
var Contacts = Restangular.all('contacts');
return {
getAll : function(){
return Contacts.getList().$object;
}
};
});
the problem is when I have tried to invoke this controller I got the following error:
Error: [$injector:unpr] Unknown provider: ContactServiceProvider <-
ContactService
http://errors.angularjs.org/1.2.19/$injector/unpr?p0=ContactServiceProvider%20%3C-%20ContactService
how can I fix that?
UPDATE:
this is the structure of my app:
I have in app.js:
.state('contacts', {
url: '/contacts',
templateUrl: 'templates/contacts.html',
controller: 'ContactController'
})
.state('todos', {
url: '/todos',
templateUrl: 'templates/todos.html',
controller: 'TodoController'
})
in the index.html i imported all th js files:
Once you have initialized a module withm, angular.module('myApp.controllers', []) again you should not use second parameter dependency([])
So,
in your controller,
`angular.module('myApp.controllers',[])` should be `angular.module('myApp.controllers')`
So,
angular
.module('myApp.controllers')
.controller('ContactController', ContactController);
ContactController.$inject = ['$scope', 'ContactService'];
function ContactController($scope, ContactService) {
console.log('here call ctrl contact');
$scope.contacts = ContactService.getAll();
}
The same applies to your service/factory,
angular.module('myApp.services')
.factory('ContactService', function(Restangular){
var Contacts = Restangular.all('contacts');
return {
getAll : function(){
return Contacts.getList().$object;
}
};
});
PS: After seeing the order of your js file injection in index.html I found the major issue.
The order of your file scripts is wrong. In ContactController you are using contactService which is not defined before it.
So change the scripts order in index.html as below.
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/services/ContactService.js"></script>
<script src="js/services/TodoService.js"></script>
<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/ContactController.js"></script>
<script src="js/controllers/TodoController.js"></script>
try to include
angular.module('myApp.controllers',['myApp.services'])
instead of
angular.module('myApp.controllers',[])
cheers
Seems the issue fixed by reorder the import of my js files as follows:
the app.js then the file services and then the controllers.
I want to use an Angular 2 Google map autocomplete and I found this directive.
When I tried to use it, it gives me this error:
errors.ts:42 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined
I dont know if I missed something. Anyway, here's the code of the directive:
import {Directive, ElementRef, EventEmitter, Output} from '#angular/core';
import {NgModel} from '#angular/forms';
declare var google:any;
#Directive({
selector: '[Googleplace]',
providers: [NgModel],
host: {
'(input)' : 'onInputChange()'
}
})
export class GoogleplaceDirective {
#Output() setAddress: EventEmitter<any> = new EventEmitter();
modelValue:any;
autocomplete:any;
private _el:HTMLElement;
constructor(el: ElementRef,private model:NgModel) {
this._el = el.nativeElement;
this.modelValue = this.model;
var input = this._el;
this.autocomplete = new google.maps.places.Autocomplete(input, {});
google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
var place = this.autocomplete.getPlace();
this.invokeEvent(place);
});
}
invokeEvent(place:Object) {
this.setAddress.emit(place);
}
onInputChange() {
console.log(this.model);
}
}
Here's how to use it:
<input type="text" class="form-control" placeholder="Location" name="Location" [(ngModel)]="address" #LocationCtrl="ngModel"
Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
If you are using google maps you have to import the Api in the ngmodule like this:
#NgModule({
declarations: [...],
imports: [...,
AgmCoreModule.forRoot({
clientId: '<mandatory>',
//apiVersion: 'xxx', // optional
//channel: 'yyy', // optional
//apiKey: 'zzz', // optional
language: 'en',
libraries: ['geometry', 'places']
})
],
providers: [...],
bootstrap: [...]
})
the library 'places' is needed to use the autocomplete module.
Than use it like this:
import {MapsAPILoader} from "#agm/core";
...
constructor(private mapsAPILoader: MapsAPILoader,
...
this.mapsAPILoader.load().then(() => {
let autocomplete = new window['google'].maps.places.Autocomplete(..., ...);
autocomplete.addListener("place_changed", () => { ...
You can take a look here: Angular 2 + Google Maps Places Autocomplete
This approach helped me to get the rid of this error. Just change the google maps api import to like this:
https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY
Then add &libraries=places to the end of URL so it looks like this:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&libraries=places">
</script>
I have coded a js file to return some values to ts files, in my angular project.
var webGlObject = (function() {
return {
init: function() {
alert('webGlObject initialized');
}
}
})(webGlObject||{})
import { Component, OnInit } from '#angular/core';
import '../../../lib/jquery-3.2.1.min.js';
import '../../../server/getSummary.js';
declare var webGlObject: any;
#Component({
selector: 'mop-designer-dashboard',
templateUrl: 'mop-designer-dashboard.component.html',
styleUrls: ['mop-designer-dashboard.component.css'],
})
export class MopDesignerDashboardComponent implements OnInit {
debugger;
scoreBoardList: any = [];
breadcrumb: any = [];
constructor() {
/* prepare breadcrumb */
this.breadcrumb = [
{
label: 'Mop Designer',
href: '/#/mop-designer'
}
];
debugger;
webGlObject.init();
}
ngOnInit() {
console.log('test');
}
}
but declare var webGlObject: any; doesn't create any object
and I get following error:
>
ZoneTask.invoke # zone.js?fad3:339
VM292602:61 Error: Uncaught (in promise): Error: Error in :0:0 caused by: webGlObject is not defined
ReferenceError: webGlObject is not defined
at new MopDesignerDashboardComponent
This is because you are creating it as a class and using as an object.
Try this:
Put following in js file:
var webGlObject = function() {
this.init= function() {
alert('webGlObject initialized');}}
And create an instance in ts file:
declare var webGlObject: any;
export class YourComponent{
constructor(){
let wegObj = new webGlObject();
wegObj.init();
}
}
I'm trying to find a way to refer to a file by using an unique name instead of a folder path. With absolute and relative path, if I move the components folder I have to refactor all the link. That is quite annoying also because by using gulp all the javascript file are moved to another directory.
In Angular 1 we just refer to the ID of the ng-template.
Is there a way to do a similar thing in Angular 2?
Additional information:
Code I'm currently using
(function(app) {
app.AppComponent =
ng.core.Component({
selector: 'my-app-test',
templateUrl: '/assets/base/components/comp-test-app/test-template.html'
})
.Class({
constructor: function() {}
});
})(window.app || (window.app = {}));
You can reference the template by relative urls by setting the moduleId of the component.
(function(app) {
app.AppComponent =
ng.core.Component({
moduleId: module.id,
selector: 'my-app-test',
templateUrl: 'test-template.html'
})
.Class({
constructor: function() {}
});
})(window.app || (window.app = {}));
Source: https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html