angular

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';

@Directive({
  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 = event.target;
    let inside = false;
    do {
      if (clickedComponent === this.elementRef.nativeElement) {
        inside = true;
        break;
      } else {
        clickedComponent = clickedComponent.parentNode;  <<<<====== see below
      }
    } while (clickedComponent);
    if(inside) {
      console.log('inside');
    } else {
      console.log('outside');
    }
  }
}

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 https://stackblitz.com/edit/ngx-bootstrap-ifmpph?file=app%2Fapp.component.html

        <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>
                        </span>
                    </div>
                </accordion-group>
            </accordion>



لینک منبع

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';
            @Component({
              selector: 'faxEmail',
              templateUrl:'./fax.email.comp.html',
               providers: [HomeService,CommonService],
            })
            export class FaxEmail {
            // here i am creating typescript class

             ngOnInit(){
               //this is simple JavaScript function 
                      var sayHello=function(){
                         alert('sayHello');
                         this.hello=function(){
//this function i am trying to call
                             alert('hello');
                         }
                         this.hello();
        //Here i am geting issue because this is using the angular //context
                      }
                      sayHello();
             }

            }

// 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: 
center">
            <select name="country" class="rounded-inputs20 select-
select col-md-3" (change)="onChangeCountry($event.target.value)">
              <option *ngFor="let country of countries"  
[value]="country.id">{{country.name}}</option>
            </select>
            <select name="city" class="rounded-inputs20 select-select 
col-md-3"  (change)="onChangeCity($event.target.value)">
              <option *ngFor="let city of cities" [value]="city.id">
{{city.name}}</option>
            </select>
            <select name="districts"  class="rounded-inputs20 select-
select col-md-3">
              <option *ngFor="let district of districts" 
[value]="district.id">{{district.name}}</option>
            </select>
          </div>

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 = 
'https://crm.easyschools.org/api/en/schools/create/create';
 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('http://crm.easyschools.org/api/en/regions')
// .map((res) => res.json())
  .subscribe(countries => {
    this.countries = countries.data;
    console.log(countries);
    this.cities = this.countries.filter(x => x.id === 1)[0].cities;
    this.districts = this.cities.filter(x => x.id === 1)[0].districts;
  });
 }
 getFile(event){
 this.imageFile =  event.target.files[0];
 }
 onSubmit(form: NgForm) {
 var data = form.value;
 let formData: FormData = new FormData();
 // debugger;

 formData.append('logo', this.imageFile, this.imageFile.name);
 formData.append('name', data.name1);
 formData.append('vision', data.vision);
 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('emails[0][email]', data.email);
 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 );

 this._http.post(this.url, formData)
  .subscribe(response => {
    // debugger;
    console.log(response);
  }, (err: HttpErrorResponse) => {
    console.log(err);
  });

 }

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:

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

<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;
        this.second.active = true;
      }
    }
  }

}

The this.second.active = 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


Issue

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//ios-shell.app/public/index.html to file:///Users//Library/Developer/CoreSimulator/Devices//data/Containers/Bundle/Application//ios-shell.app/public/#/. 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://

Implementation

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.

ViewController

class ViewController: UIViewController {
    var serenity: Serenity?

    override func viewDidLoad() {
        super.viewDidLoad()
        serenity = Serenity(self)
        serenity?.load("index")
    }

    ...
}

Serenity.swift

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)
            super.load(request)
            controller?.view.addSubview(self)
        }
    }

    ...
}

Question

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';


@Injectable()
export class DataService {

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

    constructor() { }

    update(values: any) {
        this.source.next(values);
    }
}

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() {
        this.getData();
    }

    getData() {
        this.subscription = this.dataSvc.data.take(1).subscribe(
            data => this.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() {
    this.rideStore.searchRides(this.ride).subscribe(
        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:

field1
field2
field3
field4

this.form = this.formbuilder.group({
  '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" />
                </div>

My form is marked as

 enctype="multipart/form-data"

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 = evt.target.result;
//}    

}

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.

[Route("api/quoteEngine/createPolicy")]
    [HttpPost]
    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);

        }



لینک منبع