Use HTML Link in InnerHTML to display that file in Angular - javascript

I want to display the links that are stored in a json file like this:
[
{
"heading": "Waswas",
"content": "./waswas.html"
},
{
"heading": "Flu",
"content":""
}
]
In my component.ts file I parse that to an array variable like this:
public treatmentsList:{heading: string, content: string}[] = treatments;
Then in my component.html file I have this:
<div>
<h1>
{{treatmentsList[0].heading}}
</h1>
<span [innerHTML]="getContent(treatmentsList[0].content) | async"></span>
</div>
But it shows the link instead of the file
The component.ts file:
import { Content } from '#angular/compiler/src/render3/r3_ast';
import { Component, NgModule, OnInit } from '#angular/core';
import { SafeHtml } from '#angular/platform-browser';
import { Observable } from 'rxjs';
import { ContentService } from '../content.service';
import treatments from "./treatments.json"
var heading = "hTempl"
#Component({
selector: 'app-treatment',
templateUrl: './treatment.component.html',
styleUrls: ['./treatment.component.css']
})
export class TreatmentComponent implements OnInit {
public treatmentsList:{heading: string, content: string}[] = treatments;
constructor(
private readonly contentService: ContentService
) {}
public getContent(path: string): Observable<SafeHtml> {
return this.contentService.get(path);
}
ngOnInit(): void {
}
}
app.module.ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TreatmentComponent } from './treatment/treatment.component';
import { PrgrefComponent } from './prgref/prgref.component';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
TreatmentComponent,
PrgrefComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Create a service to fetch your html documents and then sanitize them.
content.service.ts
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { DomSanitizer, SafeHtml } from '#angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
#Injectable({
providedIn: 'root',
})
export class ContentService {
constructor(
private readonly http: HttpClient,
private readonly sanitizer: DomSanitizer
) {}
public get(path: string): Observable<SafeHtml> {
const headers = new HttpHeaders({
'Content-Type': 'text/plain',
});
return this.http.get(path, {
headers,
responseType: 'text'
}).pipe(
// This is unsafe if the path and content is not under your control
map(html => this.sanitizer.bypassSecurityTrustHtml(html))
);
}
}
Then in your component.ts use the service
constructor(
private readonly contentService: ContentService
)
public getContent(path: string): Observable<SafeHtml> {
return this.contentService.get(path);
}
Finally your html
<span [InnerHTML]="getContent(treatmentsList[0].content) | async"></span>

Related

Can't bind to 'appIfRoles' since it isn't a known property of 'p'

I wanted to implement View Component Based On User Role In Angular 10 , to hide and show component. But I am block with the error above. Does anyone here has an idea about the issue? Help and idea would be much appreciated. Thanks.
#Role service code
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { Observable } from "rxjs";
/**
* The Role Service service
*/
#Injectable()
export class RolesService {
private rolesAPi: string = "https://api.npoint.io/97c436983e2fbacffc7f";
constructor(private http: HttpClient) {}
/**
* gets the user role
*/
public roles(): Observable<{ roles: string[] }> {
return this.http.get<{ roles: string[] }>(this.rolesAPi);
}
}
component.html code
<p *appIfRoles='["Admin"]'>
ADMIN CONTENT IS VIEWED
</p>
if-roles.directive.ts directive code
import { Input, OnInit, Directive, ViewContainerRef, TemplateRef, OnDestroy } from "#angular/core";
import { Subject, Subscription } from "rxjs";
import { takeUntil } from "rxjs/operators";
import { RolesService } from "../../core/services/user-role.service"
#Directive({
selector: '[appIfRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
private subscription: Subscription[] = [];
// the role the user must have
#Input() public ifRoles: Array<string>;
/**
* #param {ViewContainerRef} viewContainerRef -- the location where we need to render the templateRef
* #param {TemplateRef<any>} templateRef -- the templateRef to be potentially rendered
* #param {RolesService} rolesService -- will give us access to the roles a user has
*/
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private rolesService: RolesService
) {}
public ngOnInit(): void {
this.subscription.push(
this.rolesService.roles().subscribe(res => {
if (!res.roles) {
// Remove element from DOM
this.viewContainerRef.clear();
}
// user Role are checked by a Roles mention in DOM
const idx = res.roles.findIndex((element) => this.ifRoles.indexOf(element) !== -1);
if (idx < 0) {
this.viewContainerRef.clear();
} else {
// appends the ref element to DOM
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
})
);
}
/**
* on destroy cancels the API if its fetching.
*/
public ngOnDestroy(): void {
this.subscription.forEach((subscription: Subscription) => subscription.unsubscribe());
}
}
app.module.ts code
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
import { RouterModule } from '#angular/router';
import { LoginComponent } from './core/pages/login/login.component';
import { DashboardComponent } from './core/pages/dashboard/dashboard.component';
import { LayoutModule } from '#angular/cdk/layout';
import { SideNavComponent } from './core/components/side-nav/side-nav.component';
import { HeaderBarComponent } from './core/components/header-bar/header-bar.component';
import { UserprofileComponent } from './core/components/userprofile/userprofile.component';
import { UserInviteFormDialogComponent } from './core/components/user-invite-form-dialog/user-invite-form-dialog.component';
import { HeaderInterceptor } from './core/interceptors/header.interceptor';
import { RolesService } from './core/services/user-role.service';
import { SharedModule } from './shared/shared.module';
//import { AgmCoreModule } from '#agm/core';
import { ToastrModule } from 'ngx-toastr';
import { NgxMaskModule, IConfig } from 'ngx-mask';
import { IfRolesDirective } from './shared/directives/if-roles.directive';
// import { CoreModule } from './core/core.module';
const ngMaskConfig: Partial<IConfig> = {
validation: false,
};
#NgModule({
declarations: [
AppComponent,
IfRolesDirective,
LoginComponent,
DashboardComponent,
SideNavComponent,
HeaderBarComponent,
UserprofileComponent,
UserInviteFormDialogComponent,
,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
LayoutModule,
RouterModule,
HttpClientModule,
// CoreModule,
ToastrModule.forRoot({
preventDuplicates: true,
enableHtml: true,
progressBar: true
}),
SharedModule,
NgxMaskModule.forRoot(ngMaskConfig),
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: HeaderInterceptor,
multi: true,},
RolesService,],
bootstrap: [AppComponent]
})
export class AppModule { }
You're almost there! Just missing the export in app.module.ts
#NgModule({
declarations: [
...
IfRolesDirective,
...],
imports: [...],
exports: [IfRolesDirective]
providers: [...],
})
Try the following code.
<p *ifRoles='["Admin"]'>
ADMIN CONTENT IS VIEWED
</p>
#Directive({
selector: '[ifRoles]'
})
export class IfRolesDirective implements OnInit, OnDestroy {
private subscription: Subscription[] = [];
// the role the user must have
#Input() public ifRoles: Array<string>;
....
....
}

Service not found in NativeScript Angular

I am new to Angular nativescript, I created a service using the "ng generate service" command in my native angular application, but when importing the service I get the error that the module cannot be found
app.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptModule, NativeScriptHttpClientModule } from "#nativescript/angular";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from './components/login/login.component';
#NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule,
NativeScriptHttpClientModule
],
declarations: [
AppComponent,
LoginComponent,
],
providers: [],
schemas: [
NO_ERRORS_SCHEMA
]
})
/*
Pass your application module to the bootstrapModule function located in main.ts to start your app
*/
export class AppModule { }
ApiBackRequestService.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../environments/environment';
#Injectable({
providedIn: 'root'
})
export class ApiBackRequestService {
constructor(
private http: HttpClient) {
}
}
Login.component.ts
import { Component, OnInit } from '#angular/core';
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
#Component({
selector: 'ns-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
pokemon = [];
constructor(private api: ApiBackRequestService) { }
ngOnInit(): void {
}
}
Thanks
Is it a code-sharing project? in the Login.component.ts file just add # before the src.
change
import { ApiBackRequestService } from 'src/app/services/api-back-request.service';
to
import { ApiBackRequestService } from '#src/app/services/api-back-request.service';
this solved my problem
import { ApiBackRequestService } from '../../services/api-back-request.service';

Argument of type 'Subscription' is not assignable to parameter of type

I am trying to fetch the data from database to my angular material matdatatable. but in the ts, ı get this error: Argument of type 'Subscription' is not assignable to parameter of type ReservationList[].
Type 'Subscription' is missing the following properties from type ReservationList[]: length, pop, push, concat, and 26 more.
This is my datatable component.ts
import { Component, OnInit, ViewChild } from '#angular/core';
import {MatPaginator} from '#angular/material/paginator';
import {MatSort} from '#angular/material/sort';
import {MatTableDataSource} from '#angular/material/table';
import { ReservationList } from '../models/reservation-list.model';
import { ReservationService } from '../services/reservation.service';
#Component({
selector: 'app-mattabledata',
templateUrl: './mattabledata.component.html',
styleUrls: ['./mattabledata.component.css']
})
export class MattabledataComponent implements OnInit {
displayedColumns: string[] = ['roomName', 'name', 'progress', 'color'];
dataSource: MatTableDataSource<ReservationList>;
#ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
#ViewChild(MatSort, {static: true}) sort: MatSort;
constructor(private serv: ReservationService) {
}
ngOnInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.dataSource = new MatTableDataSource(this.serv.refreshList());
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
}
This is my service:
import { Injectable } from '#angular/core';
import {ReservationList} from '../models/reservation-list.model';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ReservationService {
reservationlist: ReservationList[];
constructor(private _http: HttpClient) { }
refreshList(){
return this._http.get("https://localhost:44389/api/reservations").subscribe(res => this.reservationlist = res as ReservationList[]);
}
}
This is my app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {FormsModule, ReactiveFormsModule} from '#angular/forms';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { MatInputModule, MatNativeDateModule } from '#angular/material';
import { SearchComponent } from './search/search.component';
import { ListComponent } from './list/list.component'
import {MatDatepickerModule} from '#angular/material/datepicker';
import {MatSelectModule} from '#angular/material/select';
import {MatTableModule} from '#angular/material/table';
import {MatButtonModule} from '#angular/material/button';
import {MatCardModule} from '#angular/material/card';
import { HttpClientModule } from '#angular/common/http';
import { MatPaginatorModule } from '#angular/material/paginator';
import { MatSortModule } from '#angular/material/sort';
import { MattabledataComponent } from './mattabledata/mattabledata.component';
#NgModule({
declarations: [
AppComponent,
SearchComponent,
ListComponent,
MattabledataComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
MatInputModule,
MatDatepickerModule,
MatNativeDateModule,
MatSelectModule,
MatTableModule,
MatButtonModule,
MatCardModule,
HttpClientModule,
MatPaginatorModule,
MatSortModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This is my reservation model:
export class ReservationList {
hotelId: number
currency: string
roomName: string
roomId: number
boardName: string
checkInDate: Date
duration: number
numberOfAd: number
numberOfChd: number
minAdtAge: number
ch1AgeMin: number
ch1AgeMax: number
ch2AgeMin: number
ch2AgeMax: number
ch3AgeMin: number
ch3AgeMax: number
price: number
PayDate: string
}
Kindly guide me how to fix this problem and get my data to the table?
Thank you
The problem is that you can't return a value in a async subscribe call. It only return a Subscription you can unsubscribe.
Do someting like:
this.dataSource = new MatTableDataSource([]);
this.serv.refreshList().subscribe(result => {
this.dataSource.data = [...result]
})
Service function
refreshList(){
return this._http.get<ReservationList[]>("https://localhost:44389/api/reservations");
}
The content in your service file is wrong. Try this code:
import { Injectable } from '#angular/core';
import {ReservationList} from '../models/reservation-list.model';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ReservationService {
reservationlist: ReservationList[];
constructor(private _http: HttpClient) { }
refreshList(){
return this._http.get("https://localhost:44389/api/reservations")
}
}
In your component file do this:
import { Component, OnInit, ViewChild } from '#angular/core';
import {MatPaginator} from '#angular/material/paginator';
import {MatSort} from '#angular/material/sort';
import {MatTableDataSource} from '#angular/material/table';
import { ReservationList } from '../models/reservation-list.model';
import { ReservationService } from '../services/reservation.service';
#Component({
selector: 'app-mattabledata',
templateUrl: './mattabledata.component.html',
styleUrls: ['./mattabledata.component.css']
})
export class MattabledataComponent implements OnInit {
displayedColumns: string[] = ['roomName', 'name', 'progress', 'color'];
dataSource: MatTableDataSource<ReservationList>;
#ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
#ViewChild(MatSort, {static: true}) sort: MatSort;
apiResponse: ReservationList[] = [];
constructor(private serv: ReservationService) {
}
ngOnInit() {
this.serv.refreshList.subscribe((res: any) => this.apiResponse = res as ReservationList[]);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.dataSource = new MatTableDataSource(this.apiResponse);
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
}
Everything else must remain the same.

Angular 2 to latest - jsonp and URLSearchParams to HttpClient and HttpParams

I am trying to upgrade this to latest but getting error to display the data. i need to refactor from Jsonp to HttpClient, and HttpParams for below code. Any help would be great.
import { Injectable } from '#angular/core';
import {Jsonp, URLSearchParams} from '#angular/http';
import 'rxjs/Rx';
#Injectable()
export class MyService {
apikey: string;
constructor(private _jsonp: Jsonp) {
this.apikey = 'my_api_key';
console.log('it works');
}
getData() {
var search = new URLSearchParams();
search.set('sort_by','popularity.desc');
search.set('api_key', this.apikey);
return this._jsonp.get('url', {search})
.map(res => {
return res.json();
})
}
}
This should be able to fix your problem. Please check doc for more info
In you module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
In your service
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs';
#Injectable()
export class MyService {
apikey: string;
constructor(private http: HttpClient){
this.apikey = 'my_api_key';
}
getData(): Observable<any> {
const params = new HttpParams()
.set('sort_by', popularity.desc)
.set('api_key', this.apikey);
return this.http.get('url', {params});
}
}

Angular 4.3.3 : Why can't I get a DI in the Service

Before I ask, I do not speak English very well.
first, I'm #angular#4.3.3 and my typescript version is ~2.3.3
Ask.
I lazy loaded the LoginModule
AppRoute
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login#LoginModule' }
];
export const AppRoutes = RouterModule.forRoot(routes);
and my
AppModule
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AppRoutes } from './routing/app.routing';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutes,
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
and
LoginModule
import { CommonModule } from '#angular/common';
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { ErrorCodeService } from '../shared/service/error-code/error-code.service';
import { LoginService } from '../shared/service/login/login.service';
import { LoginComponent } from './login.component';
#NgModule({
imports: [
HttpClientModule,
CommonModule,
FormsModule,
RouterModule.forChild([
{ path: '', component: LoginComponent }
])
],
exports: [],
declarations: [ LoginComponent ],
providers: [
ErrorCodeService,
LoginService,
],
})
export class LoginModule { }
and
LoginService
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import { ErrorCodeService } from '../error-code/error-code.service';
import { RequestCore } from '../request-core';
#Injectable()
export class LoginService extends RequestCore {
constructor(
protected http: HttpClient,
private errorCode: ErrorCodeService,
) {
super(http, '/Login');
}
public load(userid: string, passwd: string): Observable<any> {
const params = new HttpParams()
.append('id', userid)
.append('passwd', passwd);
return this.get({ params })
.map(res => {
if (res.islogin === 'true') {
return res.sendRedirect;
}
throw new Error(this.errorCode.getErrorMsg(res.reason));
});
}
}
RequestCore
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { environment } from '../../../environments/environment';
import { HttpOptions } from '../models';
export abstract class RequestCore {
constructor(
protected http: HttpClient,
private url: string,
) {
// 개발 모드에서는 proxy를 위해 url에 /dev 접두어를 붙인다.
if (environment.production === false) {
url = '/dev' + url;
}
}
protected get(options?: HttpOptions): Observable<any> {
return this.http.get(this.url, options);
}
protected post(options?: HttpOptions): Observable<any> {
return this.http.post(this.url, {}, options);
}
}
This is my error
I don't know why I can't DI in LoginService
ReuquestCore Are you making the wrong inheritance?
Teach me
Thank you!
Re:
An error occurs when the first screen is loaded.
When the next hmr is updated, no error occurs.

Categories

Resources