Title service in angular2 - javascript

I have used the Tile service of Angular, and title are getting set successfully.
Here is the code:
import { Component, OnInit } from '#angular/core';
import { Title } from '#angular/platform-browser';
#Component({
selector: 'app-homepage',
templateUrl: './homepage.component.html',
styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {
constructor(private titleService: Title) { }
ngOnInit() {
this.titleService.setTitle('homepage first title');
}
}
but the problem is that when i check the title change through "view page source", none of the changes are getting reflected and the default title in index page is showing , what can i do to resolve this.

View page source is the plain index.html source file (like you have it on your/server file system). No JavaScript is executed or anything, so obviously nothing will show.
If you would like to have that the application is already compiled, take a look at NgUniversal, to leverage server side rendering. Not sure if that will work for your use-case though.

Related

use JavaScript function in angular app.component.ts

i have a js file action.js and i want to use javaScript in angular. so when i read about it, it says that js file must be put in assets and the path must be refered in scripts array in angular.json and then using declare in ts and ngOnInit but this raises an error that the function is undefined beside that is forbidden to access the js file and MIME type checking is enabled
here is my js file function
function Di(){
console.log('ffffffffffffff');
}
the app.component.ts
import { AstMemoryEfficientTransformer } from '#angular/compiler';
import { Component, OnInit } from '#angular/core';
declare function Di(): any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
title = 'Calculator';
ngOnInit() {
Di();
}
}
angular.json
"styles": [
"src/styles.scss"
],
"scripts": ["src/assets/js/action.js"]
},
app.component.html
</div>
</div>
<script src = "/src/assets/action.js"></script>
</body>
thanks in advance
want to use js functions in angular
Try to create a di.ts file and export your function inside
export default function Di(){}
then import it into your AppComponent
import Di from 'di'
Create a ts file instead of js and then create your function like this
export fuction Di() { console.log('Di') }
then import it into your component.
If this works for you I would like you to inform me, please.
Not sure that I understand the sense of this function - should it be executed by click? Or with component creation?
Assuming that with on button click from html template,.you should add this fn as a public field into component and call it with parentheses from html

Angular 7 Dynamic variable name for imported component

In a simple angular app, I have created a test component like the one below:
test.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'test',
template: `<h1>I am a test</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class TestComponent {
}
which I import in my app module like this:
app.component.ts
import { Component } from '#angular/core';
import { TestComponent } from './test.component';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
public TestComponent = TestComponent;
dynamic = "Test";
constructor(){
console.log(TestComponent);
console.log(this.TestComponent);
console.log(this['TestComponent']);
console.log(this[this.dynamic + 'Component']);
}
}
Getting help from this topic Angular 5 Dynamic variable name, I was able to get my component name dynamically (in the real example, the dynamic variable changes depending on an API call response).
My question is if there is any way to achieve the same result without having to pass the component as a local class variable, thus avoiding this line
public TestComponent = TestComponent;
without the this keyword the dynamic variable is not working, it gives me an error
console.log([this.dynamic + 'Component']);
I tried adding the code in a stackblitz but cannot seem to be able to share it (https://github.com/stackblitz/core/issues/215), but it is quite simple to copy the two files in a new empty stackbitz (https://stackblitz.com/edit/angular-f4ars5) to replicate.
Thanks in advance.
First you need to understand the following line
this['TestComponent']
In javascript you can access class properties in two ways. Class.property or Class["property"]. So when you are writing this["TestProperty"] you are effectively saying, Get AppComponentInstance.TestProperty
So console.log([this.dynamic + 'Component']); is like writing .TextComponent with nothing on the left side.
Now based on this, what are you trying to achieve exactly? Get the type or an instance of the type? What do you want to use the type for?
What you could do though would be to declare somewhere another global class and have these properties in them. Check this one for global variable declaration.
Your json could be something like this:
export class ComponentMapping
{
private TestComponent = TestComponent;
}
And then in your class access the test component accordingly.

Angular wrapper of JS library doesn't load styles

I want to use this library https://bootstrap-datepicker.readthedocs.io/en/latest/markup.html#date-range in my application. But it has to be angular component so for the first time in my short career I wanted to create wrapper of library but I think I did something wrong becouse It doesn't looke like original picker.
This is how it should looks like:
And this is how it looks like as my angular component:
Also when I want to select only month or year it looks weird:
Ok so now time to see my component code:
import {AfterViewInit, Component, ElementRef, Input, OnInit} from
'#angular/core';
import 'bootstrap-datepicker';
declare var $;
#Component({
selector: 'cb-daterangepicker',
templateUrl: './daterangepicker.component.html',
styleUrls: ['./daterangepicker.component.scss']
})
export class DaterangepickerComponent implements OnInit, AfterViewInit {
#Input()
datepickerOptions: DatepickerOptions;
constructor(private elementRef: ElementRef) {
}
ngOnInit() {
}
ngAfterViewInit(): void {
// $(this.elementRef.nativeElement).datepicker();
$('.input-daterange input').each(function() {
$(this).datepicker('clearDates');
});
}
}
As You see there is no for example selection of range, or just start and end dates, it simply looks different so I thought it becouse not loaded styles but I might be wrong. I need Your help Guys, maybe my wrapper isn't correctly done?
*Network console with styles:
Addin styles to index.html and angular.json helped with some things:
But still range between dates is not highlighted..
Are you sure that bootstrap is correctly loaded ? you have to check this first and you have to check if the css for the library is loaded afterwards.
try to check that with the browser network console :)
othewise try to call the library style with the cdn :
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.min.css

AngularJs sanitizing and displaying html

I am trying to display dynamically html inside a div. However the div ng-bind-html does not display at all (on firefox, chrome and safari).
Looking at the other posts of this website I saw that I have to include ngSanitize.
I found this snippet here https://www.npmjs.com/package/angular-sanitize :
angular.module('myApp', ['ngSanitize']);
However I do not know where I should write this code ... Do you have any idea how I could do it ?
Thank you very much !
Here is my code :
Code in the component.ts:
import { Component, OnInit, SecurityContext } from '#angular/core';
import { DomSanitizer, SafeHtml } from '#angular/platform-browser';
#Component({
selector: 'app-player-filter',
templateUrl: './player-filter.component.html',
styleUrls: ['./player-filter.component.css']
})
export class PlayerFilterComponent implements OnInit {
text = '<h1>Test</h1><script></script>';
text_sanitized: SafeHtml;
constructor(private _sanitizer: DomSanitizer) { }
ngOnInit() {
this.text_sanitized = this.htmlProperty;
}
public get htmlProperty(): SafeHtml {
return this._sanitizer.sanitize(SecurityContext.HTML, this.text);
}
}
Code in the component.html:
<div ng-bind-html="text_sanitized"></div>
Normal: {{text}} Sanitized: {{text_sanitized}}
Output on firefox:
Normal: <h1>Test</h1><script></script> Sanitized: <h1>Test</h1>
Output console:
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
The console output shows that the sanitizing operation happenned (confirmed by the output sanitized that got rid of the script).
Wierd thing, there is no error shown in the console from having unsafe html displayed...
The 'ng-bind-html' belongs to angularJS(older version before angular 2+) so its not suppose to work or display anything with Angular 6.
Use [innerHTML] instead as mentioned in Agular Documentation:
<div [innerHTML]="text_sanitized"></div>

Angular 2 Execute JS from file using AfterViewInit

Quite new to Angular 2, and after looking around for few hours I'd like to have some help.
I have a JS file with some generic functions. For example:
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
This file contains in fact way more code. As you can imagine, I'd like to enable tooltips of all components. I can't simply include this file in index.html because subcomponents aren't present (yet) when the file is loaded.
After some digging, afterViewInit() came up. This post suggests to copy/paste JS code into ngAfterViewInit(). That's the ugly way (in my opinion)...
So here I come with 2 related questions:
1# Is there a way to execute JS code when a child component is loaded? For example, something like:
// In app.component.ts
ngAfterChildComponentLoaded(){
// JS code here
}
This solution is quite interesting because I'm not forced to implement ngAfterViewInit() with the same content in all my components. But is it possible?
2# Is there a way to import JS code instrad of copy/paste it into ngAfterViewInit()? I don't want copy/paste 300 lines of JS code into 15 differents components (for obvious reasons).
Thanks a lot for your help!
See the following for how to get external js files for a particular component in angular 2/4:
import { Component, OnInit , AfterViewInit} from '#angular/core';
import { Router } from '#angular/router';
declare var $: any;
#Component({
moduleId: module.id,
selector: 'dashboard',
templateUrl: './dashboard.html',
styleUrls: ['./dashboard.css']
})
export class DashboardComponent implements OnInit,AfterViewInit {
constructor() {}
ngOnInit() {
}
ngAfterViewInit(){
$.getScript('assets/assets/build/js/custom.min.js');
}
}
Got a less-ugly solution, if someone has a better one I'll gladly accept his answer!
ngAfterViewInit(){
$.getScript('assets/js/myscript.js', function(){});
}

Categories

Resources