How to use document.write in Angular 2 - javascript

In my normal HTML page I am having a simple 4 line code shown below:
<script>
var getData = JSON.parse(localStorage.getItem("templateType"));
document.write(getData.template_code); // in angular its wriiten as getData["template_code"]
console.log(getData.template_code);
document.getElementById("main-wrapper").innerHTML = getData.template_code;
</script>
How can I do the same in Angular 2, I have a component webview.component.html and webview.component.ts?

You can import document object inside your angular component in this way:
import { Inject, Injectable } from '#angular/core';
import { DOCUMENT } from '#angular/platform-browser';
So you use it:
#Injectable()
export class MyService {
constructor(#Inject(DOCUMENT) private document: any) {
document.write(getData.template_code);
}
}
There is a pretty similar question here.

Related

Sending whole object from one component to another in angular 2

I have a problem. I don't know how to send object from one component to another.
In first component cinema.component.html I have following function call:
<a title="Reserve" (click)="openReservationPage(repertoire)">Reserve</a>
In cinema.component.ts file, for that .html I have something like:
openReservationPage(repertoire: UpcomingRepertoire) {
this.router.navigate(['/reserve', {repertoire: JSON.stringify(repertoire)}]);
}
My app.routes.ts file contains appropriate routing:
{ path: 'reserve', component: ReserveFormComponent }
How can I use this repertoire object in another page reserve-form.component.ts and reserve-form.component.html ?
As an answer for the question in the title, i would said create a service to pass data between components.
Since its a router implementation you can pass the repertoire as a route parameter.
Follow these steps:
1)Modify the route in app.routes.ts to take a param
{ path: 'reserve/:repertoire', component: ReserveFormComponent }
2)In cinema.component.ts pass the repertoire as param
this.router.navigate(['/reserve',JSON.stringify(repertoire)]‌​);
3)Extract the param in reserve-form.component.ts
First of all you need to import
import {ActivatedRoute } from "#angular/router";
Technique 1
repertoire:any;
constructor(private activatedRoute: ActivatedRoute) {
this.repertoire = JSON.parse(activatedRoute.snapshot.params["repertoire"]);
}
Technique 2
import { Subscription } from "rxjs/Rx";
private subscription: Subscription;
repertoire:any;
constructor(private activatedRoute: ActivatedRoute) {
this.subscription = activatedRoute.params.subscribe(
(param: any) => this.repertoire = JSON.parse(param['repertoire'])
);
}
ngOnDestroy() { // here we unsubscribe to the observable
this.subscription.unsubscribe();
}
Further Explanation :
Technique 1 is adopted when you are sure that the param will be passed every time you navigate to the component.
Technique 2 is a subscription to the observable once there a param published but don't forget to unsubscribe in the ngOnDestroy() component's life cycle method to prevent memory leak.
It is more preferable because some times there a scenario that a param is passed to a component after it was created where the snapshot method wouldn't capture and it more flexible with different scenario than the basic one in technique 1.
The link below explains how you can do this. I've recently used this to create a messaging service. The example below, shows the code for a simple messaging service. It allows you to pass a number between components, just change the to I guess. You can also write out to local storage, but It seems services are more popular. Once you've got your head around them, they're easy to re-use.
Hope this helps
Sharing Data Between Angular Components - Four Methods
Message Service (PmMessageService)
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class PmMessageService
{
private pillMenuIndexBS = new BehaviorSubject <number> (null);
pillMenuIndex = this.pillMenuIndexBS.asObservable();
constructor() {}
setPillMenuIndex(index : number)
{
this.pillMenuIndexBS.next(index);
}
}
Component consuming message service, setting a value
import { Component, OnInit } from '#angular/core';
import { PmMessageService } from '../pm-message-service/pm-message.service'
import { BrowserModule } from '#angular/platform-browser';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
#Component({
selector: 'app-pm-configure',
templateUrl: './pm-configure.component.html',
styleUrls: ['./pm-configure.component.css']
})
export class PmConfigureComponent implements OnInit
{
constructor (private messageService : PmMessageService) {}
ngOnInit()
{
this.messageService.setPillMenuIndex(1);
}
}
Component consuming and subscribing.
import { Component, OnInit } from '#angular/core';
import { PmMessageService } from '../pm-message-service/pm-message.service'
import { BrowserModule } from '#angular/platform-browser';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
#Component({
selector: 'pm-bs-navbar',
templateUrl: './pm-bs-navbar.component.html',
styleUrls: ['./pm-bs-navbar.component.css']
})
export class PmBsNavbarComponent implements OnInit
{
tabActiveNumber;
constructor (private messageService : PmMessageService) {}
ngOnInit()
{
this.messageService.pillMenuIndex.subscribe(index => this.tabActiveNumber = index)
}
}

How to import js file in typescript?

I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';
#Component({
selector: 'page-success',
templateUrl: 'success.html'
})
export class SuccessPage {
constructor(public navCtrl: NavController, public navParms: NavParams) {
let centerPos = new atlan.maps.UTMK(953933.75, 1952050.75);
}
}
This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!
You have to use the declare keyword so you do not get any compilation errors. You can do the following
import { Component } from '#angular/core';
....
/* Here you are telling typescript compiler to
ignore this variable it did not originate with typescript.*/
declare var atlan: any;
#Component({
selector: 'page-success',
templateUrl: 'success.html'
})
export class SuccessPage {
....
}
In your file ../../pages/mobile.js, you must export your atlan object (if you can edit this file of course), then, you import it the same way you do with everything.

angular 2 how to import custom function to component and service

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

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

How SHOULD I inject document and window instances in angular2? [duplicate]

I have an Angular 2 application. For mocking the Document object in tests, I'd like to inject it to the service like:
import { Document } from '??'
#Injectable()
export class MyService {
constructor(document: Document) {}
}
The Title service of Angular uses the internal getDOM() method.
Is there any simple way to inject the Document to the service? Also, how should I reference it in the providers array?
This has been supported by Angular for a while.
You can use the DOCUMENT constant provided by the #angular/common package.
Description of the DOCUMENT constant (taken from the API documentation):
A DI Token representing the main rendering context. In a browser, this is the DOM Document.
An example is as shown below:
my-service.service.ts:
import { Inject, Injectable } from '#angular/core';
import { DOCUMENT } from '#angular/common';
#Injectable()
export class MyService {
constructor(#Inject(DOCUMENT) private document: Document) {}
}
my-service.service.spec.ts
import { provide } from '#angular/core';
import { DOCUMENT } from '#angular/common';
import { MyService } from './my-service';
class MockDocument {}
describe('MyService', () => {
beforeEachProviders(() => ([
provide(DOCUMENT, { useClass: MockDocument }),
MyService
]));
...
});
I'm unable to comment directly on adamdport's question (not yet 50 rep points), but here it is as stated in the angular docs.
Blockquote
#GünterZöchbauer it looks like DOCUMENT is deprecated. Any idea how to do this once it's gone? For example, how would I set the favicon dynamically?
Instead of importing from platform browser like so:
import { DOCUMENT } from '#angular/platform-browser';
Import it from angular common:
import {DOCUMENT} from '#angular/common';
in addition to #Günter Zöchbauer's answer.
Angular define DOCUMENT as an InjectionToken
export const DOCUMENT = new InjectionToken<Document>('DocumentToken');
dom_tokens.ts
And inject it with document in browser.ts
{provide: DOCUMENT, useFactory: _document, deps: []}
export function _document(): any {
return document;
}
Therefore, when we use it, we just need to inject #Inject(DOCUMENT)
or use the token directly in deps:[DOCUMENT]
import { Inject, Injectable } from '#angular/core';
import { DOCUMENT } from '#angular/common';
#Injectable()
export class MyService {
constructor(#Inject(DOCUMENT) private document) {}
}
It's the ": Document" that's causing the problem.

Categories