angular 2 how to import custom function to component and service - javascript

I have a function like this
myHelperNumber.js
function myLittleBoy(){
console.log('I see you)
}
How to use this function in User.js component or userSevicer.js service?

myHelperFunction.ts
export function myLittleBoy(){
console.log('Hello World')
}
RegisterComponent.ts
import {myLittleBoy} from 'path to myhelperfunction.ts'

export function myLittleBoy(){
console.log('I see you)
}
import { Component } from '#angular/core';
declare var myLittleBoy:any;
#Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>',
})
export class AppComponent {
constructor(private __jsmodel:JSmodelEvents){
myLittleBoy();
}
}

import {myHelperNumber} from 'your path';
export class AppComponent{
constructor(private helpNum: myHelperNumber){
// Now you can use myLittleBoy function anywhere inside the AppComponent Class
// Like below shown:
// this.helpNum.myLittleBoy();
}
}
Make sure your myHelperNumber file is in exportable format.

myHelperNumber.ts:
export const function myLittleBoy(){
console.log('I see you)
}
Then in User.ts or userService.ts
import {myLittleBoy} from './myHelperNumber';
// and just use it in this class

Related

Angular: Getter/Setter - Getter is returning undefined

I'm trying to pass a variable that is set on a component, to the parent component via a getter/setter in a service. The setter is applied correctly, but the getter returns undefined.
The below code was pulled out of another project I work on that does just fine with this code so I'm not sure why it isn't working here.
I simply just need to pass the pageTitle that is set on the child component, pass it to the parent component to display in its HTML.
Parent Component
TS: styleguide.component.ts
import { Component } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { StyleguideService } from './styleguide.service';
#Component({
selector: 'styleguide',
templateUrl: './styleguide.component.html',
host: {'class': 'route'},
})
export class StyleguideComponent {
constructor( private ss: StyleguideService ) {}
}
Relevant HTML: styleguide.component.html
<a [routerLink]="[]" aria-current="page" class="crumbs__link crumbs__link--active" [title]="ss.pageTitle">{{ss.pageTitle}}</a>
Parent Module: styleguide.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { StyleguideService } from './styleguide.service';
import { StyleguideComponent } from './styleguide.component';
import { TemplatesComponent } from './templates/templates.component';
...
#NgModule({
imports: [
CommonModule,
FormsModule,
...
],
declarations: [
StyleguideComponent,
TemplatesComponent,
...
],
exports: [
...
],
providers: [
StyleguideService
]
})
export class StyleguideModule {}
Service: styleguide.service.ts
import { Injectable } from '#angular/core';
#Injectable()
export class StyleguideService {
pageTitleS: string;
get pageTitle(): string {
console.log('get title: ', this.pageTitleS); // <-- Returns undefined
return this.pageTitleS;
}
set pageTitle(s: string) {
console.log('set title: ', s);
this.pageTitleS= s;
}
}
Child Component: templates.component.ts
import { Component } from '#angular/core';
import { StyleguideService } from '../styleguide.service';
#Component({
selector: 'templates',
templateUrl: './templates.component.html',
host: {'class': 'route__content'}
})
export class TemplatesComponent {
constructor( private ss: StyleguideService ) {
this.ss.pageTitle = "Templates";
}
}
You should implement the Service with Observables. A quick example would be something like this:
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Injectable} from '#angular/core'
#Injectable()
export class Service {
private value: BehaviorSubject<string>;
constructor() {
this.value = <BehaviorSubject<string>>new BehaviorSubject();
}
setValue(value=""){
this.value.next(value);
}
getValue() {
return this.value.asObservable();
}
}
The Parent Component would subscribe to it like so:
import {Component, OnInit} from '#angular/core'
import { Service } from './service';
#Component({
selector: 'parent-component',
template: `
<div>
<h2>Value {{value}}</h2>
<child-component></child-component>
</div>
`,
})
export class ParentComponent implements OnInit {
value:string;
constructor(private service: Service) {
}
ngOnInit(){
this.service.getValue().subscribe((newValue)=>{
this.value = newValue;
})
}
}
And the Child Component would set the value and also subscribe to it like so:
import {Component, OnInit} from '#angular/core'
import { Service } from './service';
#Component({
selector: 'child-component',
template: `
<div>
<h2>Child Value {{value}}</h2>
</div>
`,
})
export class ChildComponent implements OnInit {
value:string;
constructor(private service: Service) {
this.service.setValue('New Value');
}
ngOnInit(){
this.service.getValue().subscribe((newValue)=>{
this.value = newValue;
})
}
}
Your setter is never called. You instantiate the service using StyleguideComponent, not the TemplatesComponent which does call the setter, and the constructor of StyleguideComponent does not call the setter on the service which is why the value remains undefined.
The TemplatesComponent has an element selector templates which I do not see in the styleguide.component.html you have in the question which is why I believe TemplatesComponent is never being created.
You are not calling the setter function in your child.component.ts instead you are setting the value of variable but I think you are accessing it wrongly as you are missing the last S in the variable name. You should be doing
export class TemplatesComponent {
constructor( private ss: StyleguideService ) {
this.ss.pageTitle("Templates");
// Now to get it you should call
this.ss.pageTitle(); // Should console.log the value
}
}
Okay so it was related to my routing setup, I didn't have my child routes setup correctly so this really had nothing to do with the getter/setter after all.

Angular 5. How to track route change in Javascript file, or execute function in component level?

I have global.js script file and need to launch InitSwiper() function when route changes to '/home', but can't find how to track router in script file or launch function through home.component.ts
import { Component, OnInit } from '#angular/core';
declare var global: any;
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
ngOnInit() {
global.initSwiper();
}
}
global.js
$(function () {
"use strict";
$(window).load(function(){
pageCalculations();
$('#loader-wrapper').fadeOut();
$('body').addClass('loaded');
initSwiper();
});
...
})
If you are using CLI, you need to include that file in .angular-cli.json file inside "scripts" array.
if you want to call a function from that file in home.component.ts only, then you can declare as below
declare var global:any;
and then on
ngOnInit(){
global.InitSwiper();
}
Some have suggested guards, but it's overkill if you don't need to delay or prevent the route from being loaded.
If you import router in your constructor you can actually subscribe it like so:
import { Router, NavigationEnd } from '#angular/router';
constructor(private next: Router) {
next.events.subscribe((route) => {
if (route instanceof NavigationEnd) {
console.log(route.url);
}
});
}
In the example above it should print out the current route.
You can create a service and have your router call it in the canActivate once it goes to the required route like so. This will let you handle anything before the component gets loaded
router.module.ts
...
import {myService} from '../services/myService.service'
export const routes: Routes = [
{path: '/home', component: HomeComponent, canActivate:[myService]}
]
...
myService.service.ts
import { Injectable } from '#angular/core';
import { CanActivate, Router } from '#angular/router';
#Injectable()
export class myService implements canActivate{
canActivate{
//execute initSwiper here
if(/*success?*/){
return true;
}
else{
//redirect?
}
constructor(
private _router: Router) { }

Angular 2 Failed to compile

i created a new component in angular 2 with this:
ng g component todos
So it created the new component, I went to the component and I noted that I had a new folder with the files:
todos.component.css, todos.component.html, todos.component.spec.ts, todos.component.ts
Then I openened todos.component.ts and it had:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-todos',
templateUrl: './todos.component.html',
styleUrls: ['./todos.component.css']
})
export class TodosComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
Then I put the new second line because I am learning with a tutorial:
import { Component, OnInit } from '#angular/core';
import { TodosComponent } from './todos/todos.component';
#Component({
selector: 'app-todos',
templateUrl: './todos.component.html',
styleUrls: ['./todos.component.css']
})
export class TodosComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
When I did that and I ran the server it showed me this:
Failed to compile.
C:/angular2/proyecto/src/app/todos/todos.component.ts (2,10): Individual declarations in merged declaration 'TodosComponent' must be all exported or all local.
I'd like to know what is it bad? why does it show that error?
Thanks!
You are importing the class into it's own file.
No need to import your own component, you should import it in other files, where you use it.

Call pure javascript function from Angular 2 component

I have one file that have dozens javascript functions. What I want to do is to import that file into Angular 2 component and run init() function that is defined in "external.js" file.
import { Component, AfterViewInit } from '#angular/core';
import "../../../../assets/external.js";
#Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
export class ComponentNameComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit(): void {
// invoke init() function from external.js file
}
}
external.js is loaded using import and in ngAfterViewInit() I want to invoke init() function that is in external.js that calls all other methods in that external file.
Here is part of external.js:
function init() {
callFunction1();
callFunction2();
}
You can import and declare your external object. after then you can use it in your component.
import 'external.js'
declare var myExtObject: any;
I made an example in plunker:
https://plnkr.co/edit/4CrShwpZrDxt1f1M1Bv8?p=preview
Hope this helps.
Checkout my git project of angular 6 - I used this in login component -
https://github.com/gajender1995/Angular-HighChart-Auth
exter.js
define(["require", "exports"], function(require, exports){
exports.value = "aaa";
exports.gajender = function(){console.log(2)};
});
login.component.ts
import * as MyModule from './exter.js';
console.log('my value is', MyModule.gajender());
In tsconfig Add
"allowJs": true

Angular2 - Accessing parent component's variable from child component

I want to access a variable on the parent component from the child component and do something with it. Here is how I am doing it but it looks like its not working as it suppose to:
parent.ts
import {Component,DynamicComponentLoader,ElementRef,AfterViewInit} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ChildComponent} from './child.ts';
#Component({
selector: 'app',
template: `<div #child></div>`
})
class AppComponent implements AfterViewInit{
public parentValue = "some value."
constructor(private _loader:DynamicComponentLoader,private _elementRef:ElementRef) {}
ngAfterViewInit(){
this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => {
child.instance.log = this.callback;
});
}
callback(){
console.log(this.parentValue); //logs undefined rather than "some value"
}
}
bootstrap(AppComponent);
child.ts
import {Component} from 'angular2/core';
#Component({
selector: "child-component",
template: "<button (click)='logParentValue()' >Log Value</button>"
})
export class ChildComponent{
log:any;
logParentValue(){
this.log();
}
};
When I try to log the value of parent component's variable from the child component it always logs undefined. Any solution to this?
It seems the scope of the method is not preserved the way you pass it.
It works when passed as closureized arrow function
ngAfterViewInit(){
this._loader.loadIntoLocation(ChildComponent,this._elementRef,'child').then(child => {
child.instance.log = () => this.callback();
});
}
https://plnkr.co/edit/VQ3c2Lv5KEzHUa2ZbGLk?p=preview

Categories