How to load jsp page as template in component in angular 6 - angular6

I want to load the external jsp page content as template in my component in angular 6 application.
#Component({
selector: 'app-conrequest',
templateUrl:'mydomain.com:port/utils/registerUser.jsp',
styleUrls: ['./conrequest.component.css']
})
In the above code, I have mentioned the jsp page url, which I want to load as a template.
Please help me on this.
Thanks,
Suresh

First of all whichever external link you are using it should "return" something.
If there is no information in return it will always gives you an error.
Lets begin your answer...
Step 1- First you need to import HttpClient and Map
import { HttpClient } from '#angular/common/http';
import 'rxjs/add/operator/map';
Step 2- and your #Component decorator should look like this
#Component({
selector: 'my-template',
template: `<div [innerHtml]="myTemplate">
</div> `})
Step 3- in your class you can import your external template like...
export class TestComponent {
private myTemplate: any = '';
constructor(http: HttpClient) {
http.get('www.abc.com/index.html', {responseType: 'text'}).subscribe(data => this.myTemplate = data);
}
}
Step 4 - Also import httpClient in RootModule
imports: [
...
...
HttpClientModule
],
That's it. Try with yours.
Thanks
Sunil Sain

Related

Best way to store/display data in angular

So I have a FAQ page which I have developed in angular and I have hardcoded all the data in a html file .I just wanted to know is there a better way of displaying the data like storing it in a XML/JSON/TXT file and read the file and display it or store the XML/JSON/TXT file in angular and read form it**(if storing it where to store it)**.
.Browsed for a few articles didn't find anything helpful ,any guidance will be appreciated. I am new to angular so just looking for some advice ,thanks in advance.
If your data is static I recommend storing it in a JSON file inside your angular application under the assets folder.
You can then use Angular HttpClient to retrieve the content of the file.
In this example, the file is called 'data.json' and is stored under the 'assets' folder:
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent implements OnInit {
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('/assets/data.json').subscribe().then(data => console.log(data));
}
}
You can find more information here.

Putting anything in the constructor of Angular component results in failure of entire page

I am trying to add something to the constructor of one of my Angular components, however, anytime I put something in the constructor, it renders the entire page blank - getting rid of all of the other components and displaying just the background.
For example - this will work.
TS
#Component({
selector: 'app-cardboxes',
templateUrl: './cardboxes.component.html',
styleUrls: ['./cardboxes.component.scss']
})
export class CardboxesComponent implements OnInit {
constructor() { }
ngOnInit(): void {}
}
And this will render completely blank - removing everything, even the other components.
TS
#Component({
selector: 'app-cardboxes',
templateUrl: './cardboxes.component.html',
styleUrls: ['./cardboxes.component.scss']
})
export class CardboxesComponent implements OnInit {
constructor(private dialog: MatDialog) { }
ngOnInit(): void {}
}
For the record, it doesn't matter what is put in the constructor - it is the same result every time. The Chrome terminal says that there is a NullInjectorError - No provider for MatDialog
Is there a reason for this, or an easy solution? I do not understand why this is happening and I really need to be able to use the constructors. Do I have to make another import somewhere? Is there a configuration I am missing?
You are trying to use angular materials. Please use this comand in console.
npm i #angular/material
Open app.module and
NgModule ({....
imports: [...,
MatSliderModule,
…]
Items adsed in constructor should be imported in module

Angular 2+: Concatenate String Interpolation? [duplicate]

I am working on a tutorial involving the setting of an iframe src attribute:
<iframe width="100%" height="300" src="{{video.url}}"></iframe>
This throws an exception:
Error: unsafe value used in a resource URL context
at DomSanitizationServiceImpl.sanitize...
I have already tried using bindings with [src] with no success.
Update v8
Below answers work but exposes your application to XSS security risks!.
Instead of using this.domSanitizer.bypassSecurityTrustResourceUrl(url), it is recommended to use this.domSanitizer.sanitize(SecurityContext.URL, url)
Update
For RC.6^ version use DomSanitizer
Plunker
And a good option is using pure pipe for that:
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer} from '#angular/platform-browser';
#Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
constructor(private domSanitizer: DomSanitizer) {}
transform(url) {
return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
}
}
remember to add your new SafePipe to the declarations array of the AppModule. (as seen on documentation)
#NgModule({
declarations : [
...
SafePipe
],
})
html
<iframe width="100%" height="300" [src]="url | safe"></iframe>
Plunker
If you use embed tag this might be interesting for you:
how with angular2 rc.6 disable sanitize on embed html tag which display pdf
Old version RC.5
You can leverage DomSanitizationService like this:
export class YourComponent {
url: SafeResourceUrl;
constructor(domSanitizationService: DomSanitizationService) {
this.url = domSanitizer.bypassSecurityTrustResourceUrl('your url');
}
}
And then bind to url in your template:
<iframe width="100%" height="300" [src]="url"></iframe>
Don't forget to add the following imports:
import { SafeResourceUrl, DomSanitizationService } from '#angular/platform-browser';
Plunker sample
This one works for me.
import { Component,Input,OnInit} from '#angular/core';
import {DomSanitizer,SafeResourceUrl,} from '#angular/platform-browser';
#Component({
moduleId: module.id,
selector: 'player',
templateUrl: './player.component.html',
styleUrls:['./player.component.scss'],
})
export class PlayerComponent implements OnInit{
#Input()
id:string;
url: SafeResourceUrl;
constructor (public sanitizer:DomSanitizer) {
}
ngOnInit() {
this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);
}
}
This works me to Angular 5.2.0
fileName.Component.ts
import { Component, OnInit, Input } from '#angular/core';
import { DomSanitizer, SafeResourceUrl } from '#angular/platform-browser';
#Component({
selector: 'app-sample',
templateUrl: './fileName.component.html',
styleUrls: ['./fileName.component.scss']
})
export class FileName implements OnInit {
#Input()
url: string = "https://www.mmlpqtpkasjdashdjahd.com";
urlSafe: SafeResourceUrl;
constructor(public sanitizer: DomSanitizer) { }
ngOnInit() {
this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
}
fileName.Component.html
<iframe width="100%" height="100%" frameBorder="0" [src]="urlSafe"></iframe>
thats all folks!!!
constructor(
public sanitizer: DomSanitizer, ) {
}
I had been struggling for 4 hours. the problem was in img tag. When you use square bracket to 'src' ex: [src]. you can not use this angular expression {{}}. you just give directly from an object example below. if you give angular expression {{}}. you will get interpolation error.
first i used ngFor to iterate the countries
*ngFor="let country of countries"
second you put this in the img tag. this is it.
<img [src]="sanitizer.bypassSecurityTrustResourceUrl(country.flag)"
height="20" width="20" alt=""/>
All answers seem wrong to be honest. Using this.sanitizer.bypassSecurityTrustResourceUrl(url) only bypasses the security and treats the url as a SafeResourceUrl. However, given url may still be malicious resulting in security violations. Docs say so too: https://angular.io/api/platform-browser/DomSanitizer#bypassSecurityTrustResourceUrl
A solution would be to call sanitizer first and the pass the sanitizer return value to the bypassSecurityTrustResourceUrl like this:
this.sanitizer.bypassSecurityTrustResourceUrl(this.sanitizer.sanitize(SecurityContext.URL, url))
This way you sanitize any malicious code and then bypass the security denoting this is indeed a safe url.
I ran into this issue as well, but in order to use a safe pipe in my angular module, I installed the safe-pipe npm package, which you can find here. FYI, this worked in Angular 9.1.3, I haven't tried this in any other versions of Angular. Here's how you add it step by step:
Install the package via npm install safe-pipe or yarn add safe-pipe. This will store a reference to it in your dependencies in the package.json file, which you should already have from starting a new Angular project.
Add SafePipeModule module to NgModule.imports in your Angular module file like so:
import { SafePipeModule } from 'safe-pipe';
#NgModule({
imports: [ SafePipeModule ]
})
export class AppModule { }
Add the safe pipe to an element in the template for the Angular component you are importing into your NgModule this way:
<element [property]="value | safe: sanitizationType"></element>
Here are some specific examples of the safePipe in an html element:
<div [style.background-image]="'url(' + pictureUrl + ')' | safe: 'style'" class="pic bg-pic"></div>
<img [src]="pictureUrl | safe: 'url'" class="pic" alt="Logo">
<iframe [src]="catVideoEmbed | safe: 'resourceUrl'" width="640" height="390"></iframe>
<pre [innerHTML]="htmlContent | safe: 'html'"></pre>
This works for me
I defined an id in the iframe
<iframe id="embeddedPage"></iframe>
and in the component I used this code
export class YourComponent implements OnInit {
constructor() {}
ngOnInit(): void {
const iframe = document.getElementById('embeddedPage') as HTMLIFrameElement;
iframe.contentWindow.location.replace('your url');
}
}
I'll share this solution even if this is NOT best practice, but it happened to me once that we were not allowed to use the this.domSanitizer.bypassSecurityTrustResourceUrl(url) solution because of an automatic security warning that stopped the CI/CD pipelines.
#Component({
template: '<iframe #iframeRef></iframe>'
})
export class UnsafeUrlBypassIframeSampleComponent implements AfterViewInit {
#ViewChild('iframeRef') iframe: ElementRef<HTMLIFrameElement>;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
const MY_UNSAFE_URL = '/path/to/something';
this.renderer.setProperty(this.iframe.nativeElement, 'src', MY_UNSAFE_URL);
}
}
If it is the case that you need to bypass Angular security systems, and this will inevitably lead to vulnerabilities, it is best to do it explicitly.
I usually add separate safe pipe reusable component as following
# Add Safe Pipe
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
public transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
# then create shared pipe module as following
import { NgModule } from '#angular/core';
import { SafePipe } from './safe.pipe';
#NgModule({
declarations: [
SafePipe
],
exports: [
SafePipe
]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module
#NgModule({
declarations: [],
imports: [
SharedPipesModule,
],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
<iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>
Congratulation ! ¨^^
I have an easy & efficient solution for you, yes!
<iframe width="100%" height="300" [attr.src]="video.url"></iframe
[attr.src] instead of src
"video.url" and not {{video.url}}
Great ;)

angular2 upgradeAdapter: get reference of ng1-directive from the UpgradeAdapter?

I can add angular2 providers easy to the UpgradeAdapter:
import { HTTP_PROVIDERS } from 'angular2/http';
upgradeAdapter.addProvider(HTTP_PROVIDERS);
I can upgrade an ng1 directives (component) also quite easy:
const DirectiveNg1 = upgradeAdapter.upgradeNg1Component('DirectiveNg1');
But I need DirectiveNg1 in many places and would like to use them in angular2 components. Is it somehow possible to get a reference back?
At the moment I have specified the following in my angular2 component and it works, but I'd like to only upgradeNg1Component('DirectiveNg1') once in me main.js file.
const DirectiveNg1 = upgradeAdapter.upgradeNg1Component('DirectiveNg1');
// how can I replace the line above, and get a reference from the UpgradeAdapter
#Component({
directives: [DirectiveNg1],
...
})
I know this post is a little old but this took me ages of internet searching to work out. I don't think the documentation for this is very good.
This simplest way is if you're just going to have one module. you can define it as follows.
import { NgModule, forwardRef } from '#angular/core';
import { UpgradeAdapter } from '#angular/upgrade';
export const upgradeAdapter = new UpgradeAdapter(forwardRef(() => AppModule ));
const DirectiveNg1 = upgradeAdapter.upgradeNg1Component('DirectiveNg1');
#NgModule({
imports: [BrowserModule, HttpModule],
providers: [],
declarations: [DirectiveNg1],
exports: []
})
export class AppModule { }
now DirectiveNg1 can be used in angular2 components.

Error while getting data via JSON using Http in angular2

My .ts file has code :
/// <reference path="../../../../node_modules/angular2/typings/tsd.d.ts" />
import {Component,View,CORE_DIRECTIVES,} from 'angular2/angular2'
// import {provide} from 'angular2/angular2'
import {Http} from 'angular2/http';
#Component({
selector: 'renew',
templateUrl: 'static/components/library/renew/renew.html',
styleUrls: ['static/app.css'],
directives: [CORE_DIRECTIVES]
})
export class Renew{
http;
constructor( http:Http){ };
}
i have one .Json file having data in the form of arrays. i want to get data from json and want to show in the template. but whenever i use http in the constructor it returns error like following:
Cannot resolve all parameters for Renew(?). Make sure they all have valid type or annotations.
I have tried official angular2 website's plnkr for demo link here. but this is also not working for me(it seems that plnkr is for the alpha 37).
i am using angular2 44 alpha. and trying to get data in the child component.
am i doing something wrong here ?