Posts

Showing posts with the label typescript

@Input() value is always undefined

@Input() value is always undefined I have created a user photo component which takes an @Input() value, this value is the userId. If the value is passed in then I retrieve information from Firebase linking to this userId, if it doesn't then I do something else. user photo component @Input() Firebase My user-photo component import { Component, OnInit, OnDestroy, Input } from '@angular/core'; @Component({ selector: 'user-photos', templateUrl: './user-photos.component.html', styleUrls: ['./user-photos.component.css'] }) export class UserPhotoComponent implements OnInit { @Input() userId: string; constructor() { console.log('userId is:',this.userId); } ngOnInit() { } ngOnDestroy() { } } As you can see I have declared the userId as @Input() , now on my edit-profile component I have the following: @Input() edit-profile component <user-photos [userId]="TestingInput"></user-photo...

determine if checkbox is selected angular typescript

determine if checkbox is selected angular typescript Wanting to determine if a checkbox has been selected in the latest version of angular using an if statement. My code: <mat-menu #wj="matMenu"> <section><mat-checkbox (id)='1' (click)="$event.stopPropagation()">Cool Kids</mat-checkbox></section> </mat-menu> <div class="float-right"> <mat-action-row> <button mat-button color="primary" (click) = "generateLink()" >Generate Link</button> </mat-action-row> AND IN component.ts: generateLink() { <HTMLInputElement>document.getElementById('1') if(<HTMLInputElement>document.getElementById('1')){ console.log('y'); } } The idea is that once the submit button is pressed, the generateLink() method will evaluate to see all of the checkboxes checked by ID. If there is a better method to...

Angular update array printed via *ngFor

Angular update array printed via *ngFor How could I update array of elements which is printed via *ngFor ? I've set inputs with two-way bindings but it doesn't seem to change the original array. Also tried to set trackBy but didn't help. *ngFor trackBy Parent component template <ul> <app-skill-item *ngFor="let skill of skills; trackBy: trackByFn" [skill]="skill" (edited)="updateSkills()"></app-skill-item> </ul> In component skills described as skills: Observable<string>; and fetched from FireBase. I need to update that array and push it back to update document. skills: Observable<string>; Child chomponent <li class="lead" *ngIf="!isEditing" (click)="editStart()"> {{ skill }} </li> <li class="lead" *ngIf="isEditing" (click)="editStart()"> <input [(ngModel)]="skill" type="text" (blur)="editE...

ngModel displays identical values for different fields

ngModel displays identical values for different fields This is an Angular 5 and Firestore project. I am using a form with [(ngModel)] to update a document in the database. The update is successful. But the way [(ngModel)] displays document field values in the input boxes themselves is incorrect, e.g. the placeholders are wrong. Each input box is displaying the same field value, when they should be different. For example [(ngModel)] [(ngModel)] In the db, my doc looks like this document field1: document title field2: google field3: https://www.google.com But my input boxes show this input box 1 displays https://www.google.com input box 1 https://www.google.com input box 2 displays https://www.google.com input box 2 https://www.google.com input box 3 displays https://www.google.com input box 3 https://www.google.com Here is the HTML <ng-container *ngFor="let x of xyz | async"> update {{x.field1}} #...

Typescript image import

Typescript image import I found a solution here: Webpack & Typescript image import But i am getting error for this: [ts] Types of property 'src' are incompatible. Type 'typeof import(" .png")' is not assignable to type 'string | undefined'. Type 'typeof import(" .png")' is not assignable to type 'string'. I guess i need to cast import somehow, but cant figure out how. I am doing this in React. I saw that src attribute is defined as string | undefined , that is why error is popping. src string | undefined Here is code: import * as Logo from 'assets/images/logo.png'; HTML: <img src={Logo} alt="" /> And definition based on above mentioned solution: declare module "*.png" { const value: any; export default value; } Tsconfig: { "compilerOptions": { "baseUrl": "./", "jsx": "react", "lib": ["es5",...

Md-dialog close after notification

Md-dialog close after notification I have dialog box where user can enter data and after clicking on "create", my dialog box gets close and user gets notification. I want to close my dialog box after user get notification and if user enters wrong data, user should get notification for that too and dialog box should not get close. Currently, everything is working properly but I want my dialog box should disappear after notification (toster service). Can anyone help me with this thing so that my dialog box will stay till i get notification for success and also for error? exhibit.component.ts (main component) createExhibit(event: any) { let context = this; this.createDialogRef = this.dialog.open(CreateExhibitDialogComponent, { width: '45em', data: {} }); this.createDialogRef.afterClosed().subscribe( (newExhibit: Exhibit) => { if (newExhibit.latitude) { newExhibit.latitude = newExhibit.latitude.toString().replace(/,/g, '.'); } ...

Disable a button once clicked in Angular2

Disable a button once clicked in Angular2 I have a silly problem but i didn't know how to overcome it since i'm using Angular2 ( Typescript ) stuffs not JavaScript 's tools. I have this HTML code Angular2 Typescript JavaScript Start Simply , I want to change the button status to disabled once clicked, I found Javascript ways but none of them worked for me, any Help please ? disabled 4 Answers 4 You can use following approach without touching your component, <a class="md-btn md-btn-success" [class.disabled]="isClickedOnce" (click)="isClickedOnce = true">Start</a> another solution with code side: <button name="submitButton" #submitButton type="submit" class="btn btn-primary" (click)="onButtonClick()">Submit</button> import { ViewChild, ElementRef } from '@angular/core'; @ViewChild...

Angular printjs: ERROR TypeError: Object(…) is not a function

Image
Angular printjs: ERROR TypeError: Object(…) is not a function I'm trying to use printJS in Angular and print an image (PNG). I did the import: printJS import { printJS } from "print-js/dist/print.min.js"; Then I execute this printing code in function, according to the documentation: printJS('no-image.png', 'image'); I got following error: I can't find solution to fix this. Try to import the non minified version of the script – bambam Jun 29 at 10:48 @bambam I changed import to import { printJS } from "print-js/dist/print.js"; it compiles without any errors but the problem is the same. – XardasLord Jun 29 at 10:50 import { printJS } from ...

Dynamic column table in anguler js + Type scripts

Image
Dynamic column table in anguler js + Type scripts I want to create following dynamic column table using anguler js. According to the my requirement, column sets such as fruit, vegetables can change dynamically according to the data sets. I want to load data from json file. ex: [ { "clusterID":"1", "storeCode": "S2HK", "storeName": "store 1", "Vegetables": { "Ordered":"272", "Delivery":"250", "FR":"70%", "Gap":"22" }, "Fruit": { "Ordered":"300", "Delivery":"250", "FR":"60%", "Gap":"50" } }, { "clusterID":"1", "storeCode": "SCCC", "storeName": "store 2", "Vegetables": { "Ordered":"500...

Formatting Date/Time in TypeScript

Formatting Date/Time in TypeScript I've been having some trouble trying to get a Date object in TypeScript to format the way I want it to. Date I have a class Module which is defined as: Module export class Module { constructor(public id: number, public name: string, public description: string, public lastUpdated: Date, public owner: string) { } getNiceLastUpdatedTime(): String { let options: Intl.DateTimeFormatOptions = { day: "numeric", month: "numeric", year: "numeric", hour: "2-digit", minute: "2-digit" }; return this.lastUpdated.toLocaleDateString("en-GB", options) + " " + this.lastUpdated.toLocaleTimeString("en-GB", options); } } When I call the method with the following code: let date = new Date(1478708162000); // 09/11/2016 16:16pm (GMT) let module = new Module(1, "Test", "description", dat...

Inject a service to fill values in environment.ts file

Inject a service to fill values in environment.ts file I have an angular service ( clientAppSettings.service.ts ). It gets the config values from backend which is a json File ( appsettings.json ) angular clientAppSettings.service.ts appsettings.json I require to inject the angular service, to fill in the values in environment.ts file. So, the instrumentaionKey should be retrieved from service (clientAppSettings.service.ts). Any guide is appreciated. environment.ts instrumentaionKey Here is the environmen.ts file: environmen.ts export const environment = { production: false, appInsights: { instrumentationKey: 'some-key' } }; angular service: clientAppSettings.service.ts : clientAppSettings.service.ts @Injectable() export class ClientAppSettingService { appUrl: string = ""; constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) { this.appUrl = baseUrl; } getConfig() { return this.http.get<ClientAppSettings...

How to invoke a javascript function (generated from typescript) trapped within “System.register()” module?

How to invoke a javascript function (generated from typescript) trapped within “System.register()” module? We have moved our application from Javascript to Typescript for obvious advantages of OOP etc.. Earlier invoking a direct javascript function from Html was as straight forward as: window.MyFunction() Now with Typescript, all the files are combined into a single autogenerated .js file. In this single file, individual code of every file are isolated within System.register() . It typically looks something like: System.register() System.register("<filename>", ["<import_1>", ..., "<import_N>"], function (exports_13, context_13) { "use strict"; ... function MyFunction () { ... } // somewhere inside the external function } In short, everything is wrapped in an unnamed function, written within the .ts file. Now, I don't know how to invoke a function, which is trapped inside another function, which is in turn listed under ...

Nothing in $_POST (Http request / Angular / PHP)

Nothing in $_POST (Http request / Angular / PHP) I'm stuck with a simple issue, but I did not find any answer on Web. So, here is my code const URL = 'http://(...)/scripts/Fiabilisation_Unique.php'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type: application/json' 'reportProgress': 'true' }) (...) onClickAdresse(f : NgForm){ var adresse : Adresse= (f.value); console.log(adresse); //{adresse : "just a french adresse"} this.http.post(URL, adresse, httpOptions).subscribe( (event) => { this.temp=(event); // handle event here }, () => { console.log("Observable done ! "); } ); } But in my file 'Fiabilisation_Unique.php", when I try a simple : print_r($_POST); it prints me : Array( ) print_r($_POST); Array( ) I am pretty sure that my problem is not that complicate but I just don't figure out what is the issue. I also know that answer should not be that far but... Thank you in ...

Setting values of input fields with Angular 6

Setting values of input fields with Angular 6 I've ran into some trouble setting the value of an input element using Angular. I'm trying to set the value of dynamically created input elements in my application by this method: copyPricingToAll(): void { var copyValue: string = document.getElementById("priceInputGlobal").value; this.currentItem.orderLines.forEach(orderLine => { document.getElementById("priceInput-" + orderLine.id).setAttribute("value", copyValue); }); } I'm creating the rows like this: <ng-container *ngFor="let orderLine of currentItem.orderLines let i=index"> <tr> <td>{{getCorrectTimeString(orderLine)}}</td> <td>{{orderLine.quantity}}</td> <td><input id="priceInput-{{orderLine.id}}" type="number" value="{{orderLine.price}}"></td> </tr> </ng-container> Unfortunately .value is not rec...

How to validate date in angular 4

How to validate date in angular 4 I ma new to angular ,In my application I need to validate a date and display span message based on validation . Here I am using ngx-bootstrap datepicker . HTML: <label for="mDOB" class="control-label">Date of birth</label> <input [bsConfig]="bsConfig" type="text" maxlength="10" name="mDOB" [(ngModel)]="mUser.mDOB" #mDOB="ngModel" placeholder="Date of birth" class="form-control" bsDatepicker required> * Date of Birth is required Here I have done the reguired field validation .it's working fine Now I need to validate the date field accepts only numbers and format should be "mm/dd/yyyy". app.component.ts submitForm(newUser: User): void { // pattern="^(0?[1-9]|1[0-2])/(0?[1-9]|1[0-9]|2[0-9]|3[01])/d{4}$"; // newUser.mDOB using this I can get th...

Turning a function signature into a type?

Turning a function signature into a type? I have property that is a function and it is typed like this: /** * Function that performs the validation. */ validate: (vc: ValidationContext, object:any)=>boolean; The same type signature is used in the class constructor: constructor(validate: (vc: ValidationContext, object:any)=>boolean) {} So if I change the signature in one place then I have to change it in another. Is it possible to define a type that encapsulates the type. Something like: type ValidateType = (vc: ValidationContext, object:any)=>boolean That way the validate type can be updated in one place? validate Per the comments I got a little lucky in this question. This is how I implemented it (@cartant if you would to put this in an answer so you can get credit I'll delete it from here): /** * The type api signature for the validation function. */ type ValidationFunctionType = (vc: ValidationContext, object:any)=>boolean; ...

MongoDB returns nothing when placing the model in another file

MongoDB returns nothing when placing the model in another file I have a very basic server, which can be run in three ways: [BLOCK 2 ENABLED] / [BLOCK 1 DISABLED] Defining interfaces, schema and model in the same file. [BLOCK 2 ENABLED] [BLOCK 1 DISABLED] [BLOCK 1 ENABLED] / [BLOCK 2 DISABLED] Defining interfaces, schema and model in an external file: ./models/user.ts [BLOCK 1 ENABLED] [BLOCK 2 DISABLED] The content of [BLOCK 2] is exactly the same as the content of file: ./models/user.ts . [BLOCK 2] Just in case here you have the repository: https://github.com/napolev/mongodb-experiments Here is the code: ./server/server.ts [BLOCK 2 ENABLED] [BLOCK 2 ENABLED] import * as mongoose from 'mongoose'; import * as colors from 'colors'; /*/ // BLOCK 1: import { User, IUserDocument } from '../models/user'; /*/ // BLOCK 2: import { Document, Schema, Model, model} from "mongoose"; export interface IUser { username: string, password: string, e...