elementref – Angular 4+ Detect click in Div or nested child Divs and distinguish from other outside Divs

I have seen many Angular 2 pages that loop through a hierarchy of nativeElements. They don’t work in Angular 4, 5, …
I need to add a directive to a “workspace” DIV. There will be other Divs that are parent of workspace and others are child DIVs nested to any level.
This directive must detect a mouse click for the “workspace” div OR any of the nested divs and I must determine that it is in fact a nest child or the workspace — and NOT some other div above workspace or outside workspace.

This is derived from one of the many examples on the web:

    import {Directive, ElementRef, HostListener} from '@angular/core';

  selector: '[shMonitorInfoClicks]'
export class MonitorInfoClicksDirective {
  public elementRef;

  constructor(private myElement: ElementRef) {
    this.elementRef = myElement;

  @HostListener('document:click', ['$event'])
  public onClick(event: Event): void {
    let clickedComponent =;
    let inside = false;
    do {
      if (clickedComponent === this.elementRef.nativeElement) {
        inside = true;
      } else {
        clickedComponent = clickedComponent.parentNode;  <<<<====== see below
    } while (clickedComponent);
    if(inside) {
    } else {

When I pause in the Chrome debugger, I am able to use the console to make parentNode or parentElement work. However, I can’t get past Typescript/Angular CLI. I made sure I’m running the @latest Angular. (It’s 5).

Any help will be appreciated.
Thanks in advance.

لینک منبع

angular – Adding Chevron icon to ngx-bootsrap accordion

I have a problem changing the chevron from UP to DOWN when clicking the accordion. It seems to always result to true no matter what trick I tried and even tried other examples like this

        <accordion [closeOthers]="true">
                <accordion-group #group [isOpen]='true'>
                    <div accordion-heading class="clearfix">
                        Basic Information
                        <span class="badge badge-secondary float-right pull-right">
                            <i class="fa" [ngClass]="!group?.isOpen ? 'fa-chevron-down': 'fa-chevron-down'"></i>

لینک منبع

angular – Using extJs inside angular4. Geting context releated issue

*I am getting this issue when i am using ext inside angular. *

    //I just sharing example what i am trying to do with ext and angular.

            import { Component } from '@angular/core';
              selector: 'faxEmail',
               providers: [HomeService,CommonService],
            export class FaxEmail {
            // here i am creating typescript class

               //this is simple JavaScript function 
                      var sayHello=function(){
//this function i am trying to call
        //Here i am geting issue because this is using the angular //context


// same scenario i am geting when using ext inside angular how to solve //this .?

لینک منبع

typescript – how to append select tag option value to a web service angular 4

I have a web service to post inside it some data to create profile,

so i have a drop down list inside the form

when i try to post the data from everything on the form it works fine

but the option value from the selected option in a dropdown menu doesnt post

it gives me ‘undefined’ error

i asked the backend team and they told me it’s something in my end that i’m not binding the right data inside the json array

i need to know what is the right way to post option value

and if i selected more than one option inside the drop down, like multiselect drop down, how to post all of the options inside the array?

here is my component html:

<div class="row col-md-12" style="margin-bottom: 15px; text-align: 
            <select name="country" class="rounded-inputs20 select-
select col-md-3" (change)="onChangeCountry($">
              <option *ngFor="let country of countries"  
            <select name="city" class="rounded-inputs20 select-select 
col-md-3"  (change)="onChangeCity($">
              <option *ngFor="let city of cities" [value]="">
            <select name="districts"  class="rounded-inputs20 select-
select col-md-3">
              <option *ngFor="let district of districts" 

My component ts:

name: any[];
logo: any[];
vision: any[];
mission: any[];
address: any[];
emails: any[] = [];
numbers: any[] = [];
school_id: any[];
district_id: any[];
// latitude: any[];
// longitude: any[];
numbertitle: number;
number: number;
private url = 
 countries: any[] = []; 
 cities: any[] = []; 
 districts: any[] = []; 
imageFile: any;
schoolyears: any[] = [];
start_date: string;
end_date: string;
name_en: any[] = [];
id: number[] = [];
type: any[] = [];

private getMyBlog() {
return this._http.get('')
// .map((res) => res.json())
  .subscribe(countries => {
    this.countries =;
    this.cities = this.countries.filter(x => === 1)[0].cities;
    this.districts = this.cities.filter(x => === 1)[0].districts;
 this.imageFile =[0];
 onSubmit(form: NgForm) {
 var data = form.value;
 let formData: FormData = new FormData();
 // debugger;

 formData.append('logo', this.imageFile,;
 formData.append('name', data.name1);
 formData.append('mission', data.mission);
 formData.append('address', data.address);
 formData.append('latitude', 1);
 formData.append('longitude', 1);
 formData.append('district_id', data.districts);
 formData.append('emails[0]typescript - how to append select tag option value to a web service angular 4', data.title);
 formData.append('numbers[0]typescript - how to append select tag option value to a web service angular 4', data.numbertitle);
 formData.append('numbers[0][number]', data.number);
 formData.append('schoolyears[0][start_date]', data.start_date);
 formData.append('schoolyears[0][end_date]', data.end_date );
 formData.append( 'schooltypes[0][type_id]', 1 );, formData)
  .subscribe(response => {
    // debugger;
  }, (err: HttpErrorResponse) => {


when i try the web service api on postman and give it number (1) it gives me scode 200, the issue is with the input inside the html to read the value correctly

If anything is missing or you need more details, just comment and i will give you all the data you need, i need to know what is wrong with the district_id part

feel free to try the api on postman

لینک منبع

angular – How to prevent tab selection on ngx-bootstrap

I have two tabs with ngx-bootstrap like bellow, and I want to programatically stop tab functionality rom working:

    <tab heading="First">Tab 1 content</tab>
    <tab heading="Second">Tab 2 content</tab>

<label>Edit in progress: </label>
<input type="checkbox" [(ngModel)]="isTabSwitchEnabled">

Basically, if I have a dirty form in, say, Tab 1, I want to popup a “Discard changes?” dialog before allowing the user to “navigate” to Tab 2. I see nothing on the ngx-bootstrap tabs API that I could use.

I have an example Stackblitz where I tried working with [disabled] on tabs, and it works partways, but not fully, because I cannot set the tab programatically active (or I don’t know how):

export class MyComponent  {
  disableSwitching: boolean;
  @ViewChild('tabset') tabset: TabsetComponent;
  @ViewChild('first') first: TabDirective;
  @ViewChild('second') second: TabDirective;

  confirmTabSwitch($event) {
    if (this.disableSwitching) {
      const confirm = window.confirm('Discard changes and switch tab?');
      if (confirm) {
        this.disableSwitching = false; = true;


The = true doesn’t switch to the new tab, only marks it active. The same if I try with this.tabset.tabs[index].active = true;.

Is there a way to have this functionality? Enable and disable switching tabs? Ideally bind it to a router too (but I definitely need programatic access).

لینک منبع

ios – SecurityError (DOM Exception 18): Blocked attempt to use history.replaceState()… in Angular 5


I am receiving the following error:

[Error] ERROR – Error: Uncaught (in promise): SecurityError (DOM Exception 18): Blocked attempt to use history.replaceState() to change session history URL from file:///Users//Library/Developer/CoreSimulator/Devices//data/Containers/Bundle/Application// to file:///Users//Library/Developer/CoreSimulator/Devices//data/Containers/Bundle/Application// Paths and fragments must match for a sandboxed document.

The difference between the two urls is just the end public/index.html -> public/#/

There was a similar question asked here on StackOverflow however this was an issue between file:/// and file://


This is a custom iOS application created to run HTML SPA applications without cordova. Currently running in the Simulator on an iPhone 8 device on iOS 11.2 using the WKWebView

The web application is an Angular 5 application using {hash: true} as the routing strategy.


class ViewController: UIViewController {
    var serenity: Serenity?

    override func viewDidLoad() {
        serenity = Serenity(self)



class Serenity: WKWebView, WKScriptMessageHandler{

    var controller: ViewController?
    let config = WKWebViewConfiguration()
    var commands = Dictionary<String, (_ args: Any?) -> Any?>()

    init(_ controller: ViewController){
        self.controller = controller
        config.userContentController.addUserScript(WKUserScript(source: "window.NATIVE_DEVICE=true;", injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false))
        super.init(frame: controller.view.frame, configuration: config)

    func load(_ file: String) {
        if let html = Bundle.main.path(forResource: file, ofType: "html", inDirectory: "public"){
            let url = URL(fileURLWithPath: html)
            let request = URLRequest(url: url)



Is there a way to load the index.html file as public/ so that when angular takes over and starts routing it doesn’t cause this error?

Any other suggestions would be helpful as well

لینک منبع

angular – How to import a regular javascript library with no type definitions in Angular2?

In particular, I’m trying to use ldapjs, which has only a partial TypeScript definition @types/ldapjs.

Because it’s incomplete, I just want to use the methods in the ldapjs lib directly. Is that possible? All the tutorials/answers I find assume that there is a type definition module available. What to do when none is available?

لینک منبع

typescript – Angular 5 subscribe and unsubscrive Observable

I have to get datas from to subscribe but I get always data of the first one.

I have a data shared service :

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class DataService {

    private source = new BehaviorSubject<any>('');
    data = this.source.asObservable();

    constructor() { }

    update(values: any) {;

Before leaving search component, I call update method.
Now, I’m on the results component. I get shared data like that :

constructor(private dataSvc: DataService,
        private router: Router,
        private rideStore: RideStore) { }

    ngOnInit() {

    getData() {
        this.subscription =
            data => = data ? data : undefined,
            err => console.log(err),
            () => this._isValid()

My question is : I need shared data to subscribe to another observable. First, I construct an object ride and after i call the search method

    search() {
        rides => {
            // this.dataSvc.update(rides);
            this.rides = rides;
            console.log('results', this.ride);
        err => console.log('err', err)

The problem is I always get data from data service and not from the api call. The api works cause I intercept results in store but not in the component. So How I can stop subscribing first observable and subscribe of the second ?

لینک منبع

angular – How to compare/validate many multiple fields against each other without duplicating FormControls

I have these fields:


this.form ={
  'field1' = ['', [<control-specific-validations>]],
  'field2' = ['', [<control-specific-validations>]]
 }, { validator: isField1GreaterThanField2Validator}

More validations I need:

- field3.value must be greater than field4.value
- field3.value must be greater  than field2.value + 1
- field4.value must be less than field1.value

How do you integrate these new validation requirements into the constructed form?

لینک منبع

angular – Is it possible to map a file upload to HttpPostedFileBase in a c# web api?

I want to send a file to a web api. Does this work or do I have to use an MVC controller instead and use Request.Files?

I have a simple file upload like this

<div class="form-group">
                    <label class="control-label">Upload Custom Clause</label>
                    <input id="fileupload" type="file" onchange="FileSelected(searchForm.fileupload)" name="fileupload" />

My form is marked as


I then get the file from the uploader and assign it to a property on an object
I am not using the javascript file reader, can the actual file not map to HttpPostedFileBase in c#?

function FileSelected(fileuploader: any) {

var reader = new FileReader();    

var file = fileuploader.files[0];    

uploadedFile = file

//reader.onload = function (evt: any) {

//    filecontentStr =;


I then have a c# web api method which maps an object. The file is a property in quoteData.UploadedFile and is of type HttpPostedFileBase.

    public IHttpActionResult PostPolicy([FromBody] QuoteEngineView quoteData)

So I then have this, but UploadedFile is null… 🙁

if (policy.UploadedFile != null)
            var temppath = $"{Directory.GetCurrentDirectory()}\{policy.UploadedFile.FileName}";
            //var file = File.Create(temppath);               
            Stream str = policy.UploadedFile.InputStream;
            BinaryReader Br = new BinaryReader(str);
            clausebuffer = Br.ReadBytes((Int32)str.Length);
            string result = System.Text.Encoding.UTF8.GetString(clausebuffer);

            File.WriteAllText(temppath, result);


لینک منبع