1 . Recursive JS function with setTimeout?

Answer :

Generally speaking when you want to do breadth-first iteration, you need to use a queue (ie. FIFO). Javascript doesn't have a native queue data structure, so this just uses an array and shift, but it still gets the job done.

Here you just push everything into the queue at each level. This insures the children get pushed in after the parents, and therefore you iterate over the parents first. Normally with a graph you would also keep track of where you've been, but since this is a tree, there are no loops.


var data = [ { id: "0" }, { id: "1", children: [ { id: "1.1", children: [ { id: "1.1.1", children: [ { id: "", children: [ { id: "" }, { id: "" }, { id: "" } ] }, { id: "" }, { id: "" } ] }, { id: "1.1.2" }, { id: "1.1.3" }, ] }, { id: "1.2" }, { id: "1.3" } ] }, { id: "2" }, { id: "3" } ];

function recursive(queue) {
  var current = queue.shift();
  if (current === undefined) return
  if (current.children) {
    current.children.forEach(node => {
  setTimeout(function() {



If you want depth first you basically use a stack rather than a queue. Here it's a little strange because you care about the order of the children, so we load the stack backwards.


var data = [ { id: "0" }, { id: "1", children: [ { id: "1.1", children: [ { id: "1.1.1", children: [ { id: "", children: [ { id: "" }, { id: "" }, { id: "" } ] }, { id: "" }, { id: "" } ] }, { id: "1.1.2" }, { id: "1.1.3" }, ] }, { id: "1.2" }, { id: "1.3" } ] }, { id: "2" }, { id: "3" } ];
function recursive(stack) {
    let current = stack.pop()
    if (current === undefined) return
    if(current.children)  {

Leave a Comment

1 . BackboneJS with normal php server?

Answer :
<!doctype html>
    <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js" type="text/javascript"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js" type="text/javascript"></script>

<script type="text/javascript">
    var TodoModel = Backbone.Model.extend({
        urlRoot: '/backboneJS/todo.php',
        initialize: function(){
            // Place init message or else

    var todoItem = new TodoModel();

        success: function(todoResult){


Sticking to design pattern also, if you call your todoItem outside of nested function its likely to be executed before the actual fetch() is performed. Tested locally.

2 . Angular js,PHP what is happenening?

Answer :

Since you are POSTing a form there is not JSON data to read and decode (so $data is not an object).
Instead, there data can be accessed through the $_POST super global:

$uname = mysqli_real_escape_string($_POST["uname"]);
$passcc= mysqli_real_escape_string($_POST["pass"]);

Notice I used mysqli_real_escape_string, because you really should not use mysql_* functions.

3 . What is $implicit in angular 2?

Answer :

You can define local variable on ng-template through let-name

When angular creates template by calling createEmbeddedView it can also pass context that will be used inside ng-template

Using the key $implicit in the context object will set it's value as default. So if we write:

vcRef.createEmbeddedView(template, { $implicit: 'value' })

and we have template

<ng-template let-foo> 
 {{ foo }}

then we can think about it like

<ng-template let-foo="$implicit"> 
  {{ foo }}

so foo will equal value

Plunker Example

On the other hand if we have context like:

{ bar: 'value' }

4 . What is angular way to transform a table cell?

Answer :

So I got it with a custom directive. For those who would be interested this is my solution:


order.directive('editable', function(){

return {
    restrict : 'E',
    replace : true,
    template: '<div><span ng-hide="editMode">{{line.qty}</span><input class="span1" ng-show="editMode" type="text" ng-model="line.qty"/></div>',

    link : function(scope, element, attrs){



And in HTML, in my example it's for a qty cell only, that I need to change, but we can use it with any cell and with a little bit of modification, for example by passing cell value in the attribute of the directive and it can be universal:

<td class='line-qty'><editable></editable></td>

In my controller I initialize $scope.editMode = false the cell isn't editable by default and then in the ng-click="editLine()" handler we change $scope.editMode = true and the cell transforms in to the input field. So directives and directives and once more directives.... :)

5 . What is Angular [ngForOf] usage?

Answer :

The *ngFor directive is something Angular calls microsyntaxMicrosyntax essentially gives developers a way of configuring a directive in a more compact and simple way. You can see that something is using the microsyntax for the preceding *.

The code:

<topic *ngFor="let topic of topicdata"> </topic>

Will for example be equal to:

<ng-template ngFor let-topic [ngForOf]="topicdata">
   <topic> ... </topic>

Like in the example you have in your question.

So in short - you can replace you code with *ngFor="let topic of topicdata" and get the same result.

EDIT - TO FIX: *ngIf on the same line

Angular doesn't allow you to use two or more structural directives on the same element. So as a way of using *ngIfon the same line I recommend looping out an <ng-container> element and put your <topic> inside that one.

<ng-container *ngFor="let topic of topicdata">
   <topic *ngIf="topic.num_of_definitions > 0"> ... </topic>

6 . Angular 5 - Change body and html5 style?

Answer :

By default all angular styles are scoped to their component so adding styles to html/body tags from inside the app component (or any component) won't work.

Add those to the styles.scss file. Or if you insist you can try adding this to your @component({ ..., encapsulation: ViewEncapsulation.None })

7 . How to get the selected checkbox in matrix-table in angular?

Answer :

In your .ts file make an array of objects

hasAdd = [
  {value: 'Owner', checked: false},
  {value: 'Admin', checked: false},
  {value: 'Manager', checked: false}
hasEdit = [
  {value: 'Owner', checked: false},
  {value: 'Admin', checked: false},
  {value: 'Manager', checked: false}
hasDelete = [
  {value: 'Owner', checked: false},
  {value: 'Admin', checked: false},
  {value: 'Manager', checked: false}

Now in your template,

    <td *ngFor="let a of hasAdd">
      <input name="hasAdd" [(ngModel)]="a.checked" type="checkbox">
    <td *ngFor="let e of hasEdit">
      <input name="hasEdit" [(ngModel)]="e.checked" type="checkbox">
    <td *ngFor="let d of hasDelete">
      <input name="hasDelete" [(ngModel)]="d.checked" type="checkbox">

To get the selected options you can pass each of the object arrays to this function.

selectedOptions(myarray) { 
return myarray
          .filter(opt => opt.checked)
          .map(opt => opt.value)

8 . Handle Model Change in Angular 5 Component (Two-way-binding)?

Answer :

you can use the (ngModelChange) directive

    <input [(ngModel)]="hello" (ngModelChange)="myFunction()"/>


    import { Component } from '@angular/core';

        selector: 'my-test',
        templateUrl: './my-test.component.html',
        styleUrls: ['./my-test.component.css']
    export class MyTestComponent {
        hello: string = "bonjour";

        constructor() { }

        myFunction() {

9 . Angular 5 httpClient get Request vscode json error?

Answer :

The red wiggly lines that show up are indicating the type error. This indicates that it cannot determine the utLogon_response in type definition of myData variable. This can be solved by either of following ways:

  1. Make myData as type any (simple, quick and easier)

    this.httpClient.get('hidden') .subscribe((myData: any) => { alert(myData.utLogon_response.sessionId); })

However, my understanding is that one should use any only in extreme conditioms since this is more like defeating the very purpose of Typescript.

  1. Define proper type for myData and use it (simple, slight coding but most appropriate)

    interface IHiddenData { utLogon_response: any { sessionId: string; } }

    this.httpClient.get('hidden') .subscribe((myData: IHiddenData) => { alert(myData.utLogon_response.sessionId); })

10 . Angular 5 synchronous HTTP call?

Answer :

Using await/async

async getResult(): MyCustomObject {
    if (typeof this.result === 'undefined') 
        // save result
        this.result = await this.service.call()
        .then(resp =>resp as MyCustomObject);//Do you own cast here

    return this.result;

11 . Angular check matching objects in two arrays, TypeScript best way?

Answer :
  1. 'this.ingredients' is not accessible in the forEach, because context for that function call has changed

  2. Hence assigning 'this' to 'that' variable, which enables 'that.ingredients' will be accessible inside forEach

StackBlitz url: https://stackblitz.com/edit/angular-fulrcg

addIngredients(newIngredients: Ingredient[]) {

    let exist: boolean = false;
    let that = this;
    newIngredients.forEach(function(newIngr, newKey) {
      exist = false;
      that.ingredients.forEach(function (ingr, key) {
        if(ingr["name"] == newIngr["name"]) {
          ingr["amount"] += newIngr["amount"];
          exist = true;
      if(!exist) {

12 . Print “total” of entries, outside *ngFor?

Answer :

You can print entityList.list.length outside *ngFor to show number of values.

13 . Angular 4+ bootstrap NgbAccordion how to expand / collapse all?

Answer :

You can use the activeIds input on the accordion


Basically, assign a unique id to each of your panels

<ngb-panel *ngFor="let container ...; let i= index" title="Panel{{i}}" id="panel-{{i}}"

and declare in your component a list of the active ids (= ids of the panels that must be open)

activeIds: string[] = [];

Then modify that list when you want to open/close the panels

this.activeIds = [];//All panels closed
this.activeIds = ['panel-1', 'panel-2']; //panels 1 and 2 are open

And bind this variable to the activeIds input of the accordion

<ngb-accordion #acc="ngbAccordion" [activeIds]="activeIds"

Finally, add the buttons

<button (click)="activeIds=[]" >close all</button>
<button (click)="openAll()" >open all</button>

    this.activeIds = [/* add all panel ids here */];

14 . Using base layout elements from components?

Answer :

If I understand your question correctly, you want components to dictate what should be displayed in application layout?

Your approach won't work, because template variables do not extend between component boundries. So *ngTemplateOutlet cannot access the #toolbar variable declared in toolbar.component.

The correct approach to this problem is to create a custom structural directive.

Check out this presentation, done by Alex Rickabaugh (angular core), about creating a left-nav component with content dictated by components

15 . How to run only one timer in web?

Answer :

You can manage to not save the time into localstorage in case the difference betwen the last saved time and the new time to save is not equals to your interval period:

this.timer = setInterval(() => {
    var currentTime = new Date();
    var lastTime = localStorage.getItem('currentTime');
    if (lastTime) {
        var lastTimeTimestamp = new Date(lastTime).getTime();
        var currentTimeTimestamp = currentTime.getTime();
        if (currentTimeTimestamp - lastTimeTimestamp >= 1000) {
    } else {

}, 1000);