Angular ngFor select options with object value as default shown Ask Question

Let’s say I have an object one of statusOptions=[‘Approved’, ‘Waiting’, ‘Rejected’]

In the markup we have:

<div *ngFor="let myObject of objects">
    <select (change)="updateStatus($event.target.value)">
       <option selected>{{myObject.status}}</option>
       <option *ngFor="let status of statusOptions">{{status}}</option>
    </select>
<div>

How would I show the object’s current status as the default selected value? As of right now it will duplicate and the dropdown will show ['Approved', 'Waiting', 'Rejected', 'Approved'] if the object’s current status is 'Approved'

I do not need two way binding as I just grab the value on change and update my database.

Angular 6 – httpClient Error message not from response error data Ask Question

I am using Angular 6 httpClient and I am having issues with the error responses.

Here is the code:

postIt() {
    return this.http.post(URL, { ...httpOptions, responseType: 'text', observe: 'response' }).subscribe(
      result => {
        console.log(result);
      },
      error => {
        console.log('There was an error: ', error);
      }
    );
  }

The problem here is that it’s returning error’s like 400 (Bad Response) and not the error message that is available in httpErrorResponse.
There is a field called Error: “This record cannot be edited” … this actually is telling me what’s wrong.

How can I get that message instead of the other?

Session timeout warning popup in Angular Ask Question

I’m working on an application that has a session timeout after 30 mins of inactivity. I have a new requirement to pop up a message asking users if they’d like to keep their session active, a couple mins before they’re automatically logged out.

Right now the session is managed in what I think is a pretty unorthodox manner, and I need to try to work with what’s already there. There’s a service used by the App Module called context.service (injected as a provider) that uses a setTimeout to determine when 30 mins of inactivity has expired.

Given that I need access to that countdown, I wanted to create a mirrored timeout that executes 2 mins earlier and fires the modal, asking the user if they want to keep their session open. After injecting NgbModal into the ContextService I receive a circular reference error which seems quite reasonable. It seems a little crazy to try to populate a modal on the DOM using a provider, but I’m not sure what a viable alternative is.

Here’s the current state as it exists (with the circular reference error):

// ...
import { SessionExpirationWarning } from '../components/session-expiration-warning/session-expiration-warning.component';
// ....

constructor(
    private _http: HttpClient,
    private _injector: Injector,
    private modalSvc: NgbModal
) {
    // ...
}

// ...

setSessionTimeout() {
    if (this.appConfig === null) { return; }

    clearTimeout(this._timeoutId);
    clearTimeout(this.timeoutWarning);

    const sessionTimeOutConfig = this.appConfig.SessionTimeoutMinutes;

    const SessionTimeoutMinutes = sessionTimeOutConfig === undefined ? 5 : sessionTimeOutConfig;
    const sessionWarningMinutes = 2;

    this._timeoutId = setTimeout(() => {
        this.sessionExpired();
    }, SessionTimeoutMinutes * (60 * 1000));

    this.timeoutWarning = setTimeout(() => {
        if (!this.warningIsActive) {
            const timeOutWarningModal = this.modalSvc.open(SessionExpirationWarning);

            timeOutWarningModal.result.then((modalResponse) => {
                if (modalResponse === true) {
                    this.keepAlive(null);
                }
            });
        }
    }, sessionWarningMinutes * (60 * 1000));
}

The this.timeoutWarning was my attempt at hacking together a solution.

Generating more than one CSV File using DataTables Data on ASP.NET MVC using WebAPI and highlight Cell based on the condition Ask Question

I have ASP.NET MVC AngularJS/JQuery Application which makes WebAPI calls for returning the data back.

I have to read the data from the database table and generate two CSV files.

Here I drafted the code with sample DataTable data and here we have two different tables since their columns are different. I have to generate both the CSV Files on button Click itself.

public IHttpActionResult GenerateValidationCSVFiles(string submissionId)
    {
        try
        {
            //Based on the SubmissionID, we get data 
            //Account Table 
            DataTable tblAccount = new DataTable();

            tblAccount.Columns.Add("AccountID", typeof(int));
            tblAccount.Columns.Add("NAME", typeof(string));
            tblAccount.Columns.Add("Email", typeof(string));

            tblAccount.Rows.Add(111, "John", "John@abc.com");
            tblAccount.Rows.Add(222, "Mike", "Mike@xyz.com");
            tblAccount.Rows.Add(102, "Meghan", "Meghan@123.com");

            //Location Table
            DataTable tblLocation = new DataTable();

            tblLocation.Columns.Add("AccountID", typeof(int));
            tblLocation.Columns.Add("LocName", typeof(string));
            tblLocation.Columns.Add("Address", typeof(string));
            tblLocation.Columns.Add("CITY", typeof(string));
            tblLocation.Columns.Add("Zipcode", typeof(string));

            tblLocation.Rows.Add(111, "John", "123 Lake Dr", "Newyork", "12345");
            tblLocation.Rows.Add(222, "Mike", "456 test Dr", "Kansas", "");
            tblLocation.Rows.Add(102, "Meghan", "345 Texico Pl", "San Francisco", "");
            tblLocation.Rows.Add(212, "Steve", "8989 Williow Cir", "Chicago", "");

            //Write logic to render as CSV File data
        }
        catch (Exception ex)
        {
            ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            Log.Error("ERROR : " + ex.ToString());
            return Ok(ex.ToString());
        }
    }

Here I have sample Validation Rule like in the Location file, if Zipcode is not Empty, highlight that cell in Yellow color.

What is the best way to generate CSV files using DataTable data and highlight the Cell? Whether to highlight on the Server side or CLient side and How?

Appreciate your responses.

Thanks

Adding element to an empty JSON object – Angular Ask Question

I have an empty JSON object

export class Car {}

I have imported it in a component.ts and I would like to add some fields in a loop. Something like

aux = new Car;
for (var i = 0; i < 10; i++) {
 car.addName("name" + i);
}

My goal would be to get at the end the following object

car: {
  name1: name1;
  name2: name2;
  ....
}

I have created the JSON object empty because at the beginning I do not know how many elements or fields will have. I could create this object by javascript. I do not need to have an export class

is it possible?

Angular 5 Reactive Forms : There is no directive with “exportAs” set to “ngModel” Ask Question

I’m working on angular 5 Reactive Forms :
I had this error :
There is no directive with “exportAs” set to “ngModel”
I saw in others forums that problem can be for many reasons :
misspelling in the HTML template , forgetting to import “FormsModule” or “ReactiveFormsModule”, ….

I checked my code but i didn’t find the issue
Can you Help me please !!!

Console error :

There is no directive with "exportAs" set to "ngModel" (" 
    [(ngModel)]="user.FirstName" 
    formControlName="FirstName"
    [ERROR ->]#FirstName="ngModel" />
    <label for="firstName">{{ 'FIRST_NAME' | translate:param}}</label>")
   : ng:///AppModule/LoginComponent.html@12:15

app.module.ts:

//angular moudel
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
....

@NgModule({
  declarations: [
    .....
  ],
  imports: [
    BrowserModule,
    FormsModule, 
    ReactiveFormsModule, 
     ...
    AppRoutingMoudel,
  ],
    ...
})

LoginComponent.ts

import { Component, OnInit } from '@angular/core';
import { User } from './../../../model/user';
import {FormBuilder,FormGroup,FormControl,Validators,NgForm} from  '@angular/forms'
        ....
 export class LoginComponent implements OnInit {

     user : User;
     userLoginForm: FormGroup;

      constructor(private userLoginFormBuilder:FormBuilder) { 

        this.user = new User ("TestName", "Yagmi",
                                    "TestName@Yagmi.com", "esay", "esay");

        this.userLoginForm = this.userLoginFormBuilder.group({
                        FirstName: new FormControl (this.user.FirstName,
                                         [Validators.minLength(4),])
            });
         }
    }

LoginComponent.Html

<form class="col s12" [formGroup]="userLoginForm" (ngSubmit)="saveUserLogin()">

    <div class="row">
      <div class="input-field col s12 m6">

        <input id="firstName" 
               type="text" 
               class="validate"
               [(ngModel)]="user.FirstName" 
               formControlName="FirstName"
               #FirstName="ngModel" />

        <label for="firstName">{{ 'FIRST_NAME' | translate:param }}</label>
        <p class="data-error data-validation" *ngIf="FirstName.errors?.minlength">
          min length is 4 caracters.
        </p>
        <p class="data-error data-validation" *ngIf="FirstName?.touched">
          touched.
        </p>

      </div>
    </div>
  </form>

user.ts

export class User {
    constructor(
        public FirstName: string,
        public LastName: string,
        public Email: string,
        public Passeword: string,
        public ConfirmPasseword: string
   )
}

Mute and autoplay video on mobile devices using angular 4 Ask Question

I am using html5 video tag in angular 4 app to autoplay video in background. I am unable to auto mute the video and because of that video is not autoplaying on mobile devices. Code I am using is:

<video playsinline autoplay loop controls = "controls" muted = "muted">
   <source src="banner-video.mp4" type="video/mp4" />
   <source src="banner-video.webm" type="video/webm" />
</video>

PS: Video is autoplaying on laptop but is not getting auto muted.