1 . Match two object keys and display another object key value in angular 4

Answer :

Use array find:

 

var languages = [
    {"name": "english", "iso_639_2_code": "eng"},
    {"name": "esperanto","iso_639_2_code": "epo"},
    {"name": "estonian","iso_639_2_code": "est"}
];
var user = [{name: "john",language: "eng",country: "US"}];

var language = languages.find(l => l.iso_639_2_code === user[0].language);
var languageName = language && language.name; // <-- also prevent error when there is no corresponding language found
console.log(languageName);

Leave a Comment

Name  
  Email   
Message
1 . BackboneJS with normal php server?
 

Answer :
<!doctype html>
<html>
<head>
    <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>
</head>
<body>

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

    var todoItem = new TodoModel();

    todoItem.fetch({
        success: function(todoResult){
            console.log(todoResult);
            console.log(todoItem.get(1));
        }
    });


</script>
</html>

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:

<?php 
$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 }}
</ng-template>

then we can think about it like

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

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:

Directive:

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>
</ng-template>

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>
<ng-container>


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,

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

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()"/>

code:

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

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

        constructor() { }

        myFunction() {
            console.log(this.hello);
        }
    }

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()
        .toPromise()
        .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;
    //debugger;
    console.log(this.ingredients);
    newIngredients.forEach(function(newIngr, newKey) {
      exist = false;
      console.log(newIngr);
      that.ingredients.forEach(function (ingr, key) {
        if(ingr["name"] == newIngr["name"]) {
          ingr["amount"] += newIngr["amount"];
          exist = true;
        }
      });
      if(!exist) {
        **that.ingredients**.push(newIngr);
      }
    });

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

https://ng-bootstrap.github.io/#/components/accordion/api

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>

openAll()
{
    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) {
            localStorage.setItem('currentTime',String(currentTime));
        }
    } else {
        localStorage.setItem('currentTime',String(currentTime));
    }

}, 1000);