Angular 5 add dynamic html file into DIV - html

I am very new to Angular, I am trying to insert the html file as my string and insert into DIV element
I have my search.component.html called
<div #ID></div>
components.ts
import { Component} from '#angular/core';
#Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent {
constructor() {}
let ServerResponseHtml = '<div><input type="text"/><input type="text"/><span class="btn btn-outline-primary btn-sm" (click)="open(content)">View Document</span></div>';
document.getElementById("DIV").innerHTML = ServerResponseHtml;
}
I am getting the response from server as complete html markup, Just I need to append into my DOM and display the content, the markup can have inline styles also.
I tried for <div [innerHTML]="ServerResponseHtml"></div> and <div innerHTML="{{ServerResponseHtml}}"></div> but this is not displaying as html it is displayed as text.

We need to use the safehtml for displaying the html.
We need to create the Pipe for this. safe-html-pipe.ts
import {DomSanitizer, SafeHtml} from '#angular/platform-browser';
import {Pipe, PipeTransform} from '#angular/core';
#Pipe({name: 'safehtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value): SafeHtml {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
component.ts
We need to import the pipe
import {Component, NgModule, Pipe, PipeTransform} from '#angular/core'
import {BrowserModule} from '#angular/platform-browser'
import { FormsModule } from '#angular/forms';
import { DomSanitizer } from '#angular/platform-browser'
import { SafeHtmlPipe } from './safe-html-pipe';
#Component({
selector: 'app-root',
template:
`<div [innerHtml]="safeHtmlContent | safehtml">
</div>"})`
export class AppComponent {
name:string;
safeHtmlContent : string;
constructor() {
this.name = 'Angular2'
this.safeHtmlContent = '<html><head><title>Hello safe</title></head><body><h1>hello world Hello Umesh</h1></body></html>';
}
}
Hope this helps :).

Related

How to call a component from other component in angular 7

I have a checkbox,if that checkbox is checked, I need to show alert message on load the application.But problem is that checkbox is in header component and it is linked with home component.So when I will be in home page and if that checkbox is checked, I need to show alert message on load the application. Here is the code below,
header.component.html
<div><input checked type="checkbox">Other-component</div>
header.component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from "#angular/router";
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor(public router: Router){}
ngOnInit() {}
}
home.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import Speech from 'speak-tts';
import { RxSpeechRecognitionService, resultList, } from '#kamiazya/ngx-speech-recognition';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [ RxSpeechRecognitionService ]
})
export class HomeComponent implements OnInit {
showit:any;
nestedjson:any;
constructor(private formBuilder: FormBuilder,public service: RxSpeechRecognitionService) {
}
ngOnInit() {
}
}
1) To the question in your headline: How to call a component from other component
You can give the header component a reference id inside the home template.
<app-header #header></app-header>
Then you can access the header component through a ViewChild in your home component.
#ViewChild('header') headerComponent: HeaderComponent;
But this does not seem to be very good practice for your needs. Consider using a service and subscribe to a Subject by using RxJs Observables. Or much simpler in your case: just use two-way-data-binding.
2) The way you should actually communicate between components: two way data binding
header.component.ts
export class HeaderComponent implements OnInit {
#Input() isChecked: boolean;
#Output() isCheckedChanged = new EventEmitter<boolean>();
constructor(public router: Router){}
ngOnInit() {
}
}
header.component.html
<input [(ngModel)]="isChecked" type="checkbox">
home.component.ts
export class HomeComponent implements OnInit {
isChecked: boolean;
constructor() {}
ngOnInit() {
}
}
home.component.html
<app-header [(isChecked)]="isChecked"></app-header>
Edit: in your case you also don't need two way binding since you don't need any feedback from the HeaderComponent. One way data binding will be fine. Then you can remove the line
#Output() isCheckedChanged = new EventEmitter<boolean>();
And in Home template don't use banana in the box syntax [()], instead just use []:
<app-header [isChecked]="isChecked"></app-header>
You can make use of a service which is defined at the root level.And then with the help of a service you can either emit or use Subjects to capture in your home component.

Appending a translated string in html (angular 6) with a property of an object

I have a myapp.component.ts file in which I have the following
import { Component, Input, OnInit, ViewChild } from '#angular/core';
import { isNullOrUndefined } from 'util';
import { AuthenticationService } from '/services';
import * as _ from 'lodash';
#Component({
selector: 'cd-myapp',
templateUrl: './myapp.component.html',
styleUrls: ['./myapp.component.scss']
})
export class myAppComponent implements OnInit {
#Input() car: Car;
constructor(
private authenticationService: AuthenticationService) { }
ngOnInit() {
//my code
}
}
I have another component, in which I have the following in the carhandler.component.ts file :
import { Component, OnInit, Input, Output, EventEmitter } from
'#angular/core';
#Component({
selector: 'app-carhandler',
templateUrl: './carhandler.component.html',
styleUrls: ['./carhandler.component.scss']
})
export class CarhandlerComponent implements OnInit {
#Input() field: string;
#Input() value: string;
constructor() { }
ngOnInit() {
}}
In my myapp.component.html I would like to append. I tried this :
<app-carhandler [field]="Testing"
[value] = "'DESCRIPTION' | translate" +'-'+{{car.color}}>
</app-carhandler >
It does not work. How should I tackle this problem?
I'm sorry, i'm having no explanation why, but it works this way:
<app-carhandler [field]="Testing"
[value] = "(('DESCRIPTION' | translate) +'-'+ car.color)">
</app-carhandler >

Angular and Typescript Sending Post Request

I have a simple page with angular and typescript with just 1 button and 1 text field. I want to make a post request to a link that posts the string written in text box.
my button html:
<a class="button-size">
Add Customer
</a>
and button ts file:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'customer-button123',
templateUrl: './blabla',
styleUrls: ['./clacla']
})
export class AddCustomerButtonComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
text box html:
<mat-form-field>
<input matInput placeholder="Customer Name">
</mat-form-field>
text box ts file:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'customer-text-field',
templateUrl: './blabla2',
styleUrls: ['./clacla2']
})
export class CustomerTextFieldComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
and simple wrapper page html is:
<div class="input-label">
<mg-customer-text-field></mg-customer-text-field>
</div>
<div>
<mg-customer-button123></mg-customer-button123>
</div>
How can i send a post reques to link localhost8080/admin/addCustomer ?
If you hosting your front end at port: 4200 (default Angular port serve) and you want to send a request to http://localhost8080/admin/addCustomer, you will need a proxy configuration. You can see right here for more info: https://itnext.io/angular-cli-proxy-configuration-4311acec9d6f
You use the HttpModule
I use a service to separate http requests.
Example
import { Component, OnInit } from '#angular/core';
import { ApiService } from '../../services/api.service';
#Component({
selector: 'customer-button123',
templateUrl: './blabla',
styleUrls: ['./clacla']
})
export class AddCustomerButtonComponent implements OnInit {
data: any;
results: any;
constructor(private apiService: ApiService) { }
ngOnInit() {
}
getDataFromApi() {
this.apiService.getData(this.data).subscribe(results => {
this.results = results;
});
}
ApiService
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ApiService {
apiUrl: string = environment.apiUrl;
constructor(private http: HttpClient) {}
getData(data): any {
return this.http.get(`http://localhost:8080/api/get-data`);
}
html
<div class="input-label">
<mg-customer-text-field [(ngModel)]="data"></mg-customer-text-field>
</div>
<div>
<mg-customer-button123 (click)="getDataFromApi()"></mg-customer-button123>
</div>

Display data from json array using angular4

I am new to angular so please help me. I have an api returning an array of objects containing name, place id.
I need to display this in different cards on my html page, the cards being a widget.
in the parent component under the ngOnInit() section how do I access this json data and loop through the array in order to display it on my page as different cards?
Thank you in advance.
import { Component, OnInit } from '#angular/core';
import {HttpClient} from '#angular/common/http';
import { Observable } from 'rxjs/observable';
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
showSplash = true
//public events: any = [];
events = [];
constructor(private http : HttpClient) { }
ngOnInit() {
this.showSplash = true
this.http.get("/events").subscribe(data => {
console.log("EVENTS ARE: ", data);
this.events = data;
console.log(this.events)
})
}
ngAfterViewInit(){
setTimeout(() => {
this.showSplash = false
}, 3000);
}
}
This will get you the events you want.
import { Component, OnInit, OnDestroy } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit, OnDestroy {
showSplash = true
events = [];
subscription: Subscription;
constructor(private http: HttpClient) {}
ngOnInit() {
this.subscription = this.http.get("/events").subscribe(data => {
this.events = data;
this.showSplash = false;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
You will have to implement a Child Component(EventComponent probably with the selector app-event) that will accept an event object as an #Input property. Then in your HomePageComponent Template, you can loop through the events like this:
<div *ngFor="let event of events">
<app-event [event]="event"></app-event>
</div>
Alternatively:
You can use the async pipe in your HomePageComponent's Template to avoid manually unsubscribing from the Observable Subscription. Your HomePageComponent Class code will change to:
import { Component, OnInit } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-home-page',
templateUrl: './home-page.component.html',
styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
events$;
constructor(private http: HttpClient) {}
ngOnInit() {
this.events$ = this.http.get("/events");
}
}
And then in HomePageComponent's Template:
<div *ngFor="let event of events$ | async">
<app-event [event]="event"></app-event>
</div>
Here's how your EventComponent would look like in this case:
import { Component, Input, OnChanges } from '#angular/core';
#Component({
selector: 'app-event',
templateUrl: './event.component.html',
styleUrls: ['./event.component.css']
})
export class EventComponent implements OnChanges{
#Input() event;
ngOnChanges() {
this.events$ = this.http.get("/events");
}
}

How to detect changes in the value of an input text on key press Angular 6

I need to handle something on html input text, distinctUntilChanged not working properly, text cycle by each character in Angular 6.
How do I solve it?
import { Component, Output, EventEmitter, ElementRef, ViewChild, OnInit }
from '#angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime, map, distinctUntilChanged, filter } from
rxjs/operators'
#Component({
selector: 'app-child',
template: `
<input #inputSearch placeholder="Write something"/>`
})
export class HijoComponent implements OnInit {
#Output() inputText: EventEmitter<any> = new EventEmitter();
#ViewChild('inputSearch') inputSearch: ElementRef
constructor(){
}
ngOnInit(){
fromEvent(this.inputSearch.nativeElement, 'keyup').
pipe(
map((evt: any) => evt.target.value),
filter(res => res.length > 2),
debounceTime(1000),
distinctUntilChanged()
).subscribe((c : string)=> {
this.inputText.emit(c)
});
}
}