Getting Date Formatted and Printed to Screen in Angular 2 App - javascript

I am trying to get the date pipe I'm using in my Angular app to parse out correctly when using it in the template within an input. Initially, before formatting the date, the code looked like this:
<input class="app-input" [readonly]="!hasAdminAccess"
[(ngModel)]="staff.profile.hireDate" placeholder="None"
[field-status]="getPropertyStatus('profile.hireDate')"/>
The closest I've gotten with the date pipe is this:
<input class="app-input"
{{ staff.profile.hireDate | date:'shortDate' }} placeholder="None"
[field-status]="getPropertyStatus('profile.hireDate')"/>
But what that prints to the view is this (literally this):
> <input class="app-input" 3/18/2014 placeholder="None"
> [field-status]="getPropertyStatus('profile.hireDate')"/>
Now, you'll notice that the correctly formatted date is there (and the date transformation is happening successfully, to make it this:
3/18/2014
However, I don't want the rest (obviously). How can I rework the syntax here so as to get just the date to print? I've stared at it and tried a few tweaks, but as of yet haven't been able to get it to work.

You can use the get and set functions in typescript and ngModelChanged property to modify the ngModel after it has been set.
Component Template :
<input class="app-input" [(ngModel)]="hireDate" (ngModelChange)="dateChanged($event)"/>
Component Class :
import { Component } from '#angular/core';
import { DatePipe } from '#angular/common';
#Component({
selector: 'my-app',
template: `
<div>
<button (click)="setDate()">Set Date</button>
<input class="app-input" readonly="true" [(ngModel)]="hireDate" (ngModelChange)="dateChanged($event)" placeholder="None"/>
</div>
`,
})
export class App {
name:string;
staff: any;
myDate: any;
private _hireDate;
dateChanged(value) {
this.hireDate = this.datePipe.transform(value, 'shortDate');
}
set hireDate(value) {
this._hireDate = this.datePipe.transform(value, 'shortDate');
}
get hireDate() {
return this._hireDate;
}
setDate() {
this.hireDate = '10-03-1993';
}
constructor(private datePipe: DatePipe) {
}
}
The value of the input will be set whenever the input changes, so it might cause a UX issue, as the user would not be able to enter his prefered date. A workaround would be to call the date changed function whenever the user has entered his date. (For eg. via a button click).
I believe the set and get functions work only for class variables, in your case you have a object property. Modifying the set function as shown below would work.
set hireDate(value) {
this._hireDate = this.datePipe.transform(value, 'shortDate');
this.staff.profile.hireDate = this._hireDate;
}
I have also added a plunkr here.

Related

Angular: How to assigne value to variable in specific component from input of different template

I'm making daterangepicker as Angular Component that is wrapper of JS library (https://bootstrap-datepicker.readthedocs.io/en/latest/). My problem is that I don't know how to pass value that is in input of datepicker to variable that is in other component (that where I want to use my daterangepicker). This is how I made daterangepicker component:
import {AfterViewInit, Component, Input, OnInit} from '#angular/core';
import 'bootstrap-datepicker';
declare var $;
#Component({
selector: 'cb-daterangepicker',
templateUrl: './daterangepicker.component.html',
styleUrls: ['./daterangepicker.component.scss']
})
export class DaterangepickerComponent implements OnInit, AfterViewInit {
#Input()
datepickerOptions: DatepickerOptions;
constructor() { }
ngOnInit() { }
ngAfterViewInit(): void {
$('.input-daterange').datepicker(this.datepickerOptions).on('changeDate', function() {
var startDate =$('#start').datepicker('getDate');
var endDate= $('#end').datepicker('getDate');
console.log(startDate + " to " + endDate);
});
}
}
And the template looks like this:
<div class="input-daterange input-group" id="datepicker">
<input type="text" class="input-sm form-control" id="start" />
<span class="input-group-addon">to</span>
<input type="text" class="input-sm form-control" id="end" />
</div>
Maybe I did something wrong but console.log returns me correct values so I think this two things are good.
What I want to achive:
In other component - let me name it 'exampleComponent' I have two variables: startDate and endDate, I need to pass values that I chose in daterangepicker to this variables every time I change the value. What I suppose to do?
You have to use #Output decorator,
First create new property in class DaterangepickerComponent mark it as #Output and assign EventEmitter Instance to it (you need import it)
#Output dateOutput = new EventEmitter<Object>();
Next in your callback when you have
console.log(startDate + " to " + endDate);
You need to use:
this.dateOutput.emit({startDate, endDate});
When you use your component you need to pass callback attribute to it
<cb-daterangepicker dateOutput="callback($event)">
after that when you choose date in datepicker callback method will be called

Angular modal not updates with component variable change

I am using a component for sending SMS and it is added to the nagigation bar component like this :
<ng-template #smsModal let-c="close" let-d="dismiss">
<div class="modal">
<app-sms></app-sms>
</div>
</ng-template>
The sms component HTML looks likes the following :
<form>
<input type="text" [(ngModel)]="send.mobileNumber" #ctrl="ngModel" name="mobileNumber">
<button class="send-SMS-btn ripple" (click)="sendMessage()" [disabled]="textSending">
<span *ngIf="!textSending">Send Message</span>
<app-spinner *ngIf="textSending"></app-spinner>
</button>
<div class="textmsg text-danger" *ngIf="textError">{{textError}}</div>
<div class="textmsg success" *ngIf="textSuccess">{{textSuccess}}</div>
</form>
the method sendMessage() has the following code :
this.textSending = false;
if (_.isEmpty(this.send.mobileNumber)) {
this.textError = "Please enter a valid phone number";
return false;
}
this.textSending = true;
this.textSuccess = null;
// API call and stuff
}
When I console the this.textError, it is giving the correct error message, but this is not updated in view. The error container div itself is not populated and also the spinner is not showing. Somehow, the view is not detecting changes . The API call is triggered, but it also not showing error message, even if it is showing in console. How this can be fixed ?
Probably need to restart the digest cycle again. use the changeDetectorRef service
constructor(
private changeDetectorRef: ChangeDetectorRef,
) {
}
call the detectChanges method inside sendMessage method
if (_.isEmpty(this.send.mobileNumber)) {
this.textError = "Please enter a valid phone number";
return false;
}
this.textSending = true;
this.textSuccess = null;
this.changeDetectorRef.detectChanges(); // start the cycle again
A typical way for me to address input data from passed into a component is to declare the input as a BehaviorSubject.
For example:
import { Component, Input } from '#angular/core';
import { BehaviorSubject, Observable } from 'rxjs/Rx';
#Component({
selector: 'my-component-selector',
templateUrl: './my.component.html'
})
export class MyComponent {
#Input()
public set yourErrorTextMessage(data) {
this.yourErrorTextMessageSubject.next(data);
};
private yourErrorTextMessageSubject = new BehaviorSubject<string>("");
}
What this does is tie the actual value to the behavior subject, and the template gets notified of any changes to it, including values prior to the template initializing. Thus your error message can be updated asynchronously and your component will get the value for the last error message whether it happened before or after the initialization.

angular5:ngFor works only in second button click

My scenario as follows
1) When the user enters a keyword in a text field and clicks on the search icon it will initiate an HTTP request to get the data.
2)Data is rendered in HTML with ngFor
The problem is on the first click the data is not rendered in HTML but I am getting the HTTP response properly, and the data rendered only on second click.
component.ts
export class CommerceComponent implements OnInit {
private dealList = [];
//trigger on search icon click
startSearch(){
//http service call
this.getDeals();
}
getDeals(){
this.gatewayService.searchDeals(this.searchParams).subscribe(
(data:any)=>{
this.dealList = data.result;
console.log("Deal list",this.dealList);
},
(error)=>{
console.log("Error getting deal list",error);
this.dealList = [];
alert('No deals found');
}
);
}
}
Service.ts
searchDeals(data){
var fd = new FormData();
fd.append('token',this.cookieService.get('token'));
fd.append('search',data.keyword);
return this.http.post(config.url+'hyperledger/queryByParams',fd);
}
HTML
//this list render only on second click
<div class="deal1" *ngFor="let deal of dealList">
{{deal}}
</div>
UPDATE
click bind html code
<div class="search-input">
<input type="text" [(ngModel)]="searchParams.keyword" class="search" placeholder="" autofocus>
<div class="search-icon" (click)="startSearch()">
<img src="assets/images/search.png">
</div>
</div>
According to Angular official tutorial, you could have problems if you bind a private property to a template:
Angular only binds to public component properties.
Probably, setting the property dealList to public will solve the problem.
Remove "private" from your dealList variable. That declaration makes your component variable available only during compile time.
Another problem: you are implementing OnInit in yout component but you are not using ngOnInit. Angular is suposed to throw an error in this situation.
My suggestion is to switch to observable:
I marked my changes with CHANGE
component.ts
// CHANGE
import { Observable } from 'rxjs/Observable';
// MISSING IMPORT
import { of } from 'rxjs/observable/of';
export class CommerceComponent implements OnInit {
// CHANGE
private dealList: Observable<any[]>; // you should replace any with your object type, eg. string, User or whatever
//trigger on search icon click
startSearch() {
//http service call
this.getDeals();
}
getDeals() {
this.gatewayService.searchDeals(this.searchParams).subscribe(
(data:any)=>{
// CHANGE
this.dealList = of(data.result);
console.log("Deal list",this.dealList);
},
(error)=>{
console.log("Error getting deal list",error);
// CHANGE
this.dealList = of([]);
alert('No deals found');
}
);
}
}
HTML
<!-- CHANGE -->
<div class="deal1" *ngFor="let (deal | async) of dealList">
{{deal}}
</div>
Try this:
this.dealList = Object.assign({},data.result);
Better do this inside the service.
By default, the angular engine renders the view only when it recognizes a change in data.

what is the equevalant for getelementbyid in angular 2 [duplicate]

I have a code:
document.getElementById('loginInput').value = '123';
But while compiling the code I receive following error:
Property value does not exist on type HTMLElement.
I have declared a var: value: string;.
How can I avoid this error?
Thank you.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
here is working example
Update
okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit will not throw any error because it will render after template loading
(<HTMLInputElement>document.getElementById('loginInput')).value = '123';
Angular cannot take HTML elements directly thereby you need to specify the element type by binding the above generic to it.
UPDATE::
This can also be done using ViewChild with #localvariable as shown here, as mentioned in here
<textarea #someVar id="tasknote"
name="tasknote"
[(ngModel)]="taskNote"
placeholder="{{ notePlaceholder }}"
style="background-color: pink"
(blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }}
</textarea>
import {ElementRef,Renderer2} from '#angular/core';
#ViewChild('someVar') el:ElementRef;
constructor(private rd: Renderer2) {}
ngAfterViewInit() {
console.log(this.rd);
this.el.nativeElement.focus(); //<<<=====same as oldest way
}
A different approach, i.e: You could just do it 'the Angular way' and use ngModel and skip document.getElementById('loginInput').value = '123'; altogether. Instead:
<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>
and in your component you give these values:
username: 'whatever'
password: 'whatever'
this will preset the username and password upon navigating to page.
Complate Angular Way ( Set/Get value by Id ):
// In Html tag
<button (click) ="setValue()">Set Value</button>
<input type="text" #userNameId />
// In component .ts File
export class testUserClass {
#ViewChild('userNameId') userNameId: ElementRef;
ngAfterViewInit(){
console.log(this.userNameId.nativeElement.value );
}
setValue(){
this.userNameId.nativeElement.value = "Sample user Name";
}
}

Angular 2 input value not updated after reset

I have a simple input that I want to reset the value to empty string after I am adding hero. The problem is the value is not updated. why?
#Component({
selector: 'my-app',
template: `
<input type="text" [value]="name" #heroname />
<button (click)="addHero(heroname.value)">Add Hero!</button>
<ul>
<li *ngFor="let hero of heroes">
{{ hero.name }}
</li>
</ul>
`,
})
export class App {
name: string = '';
heroes = [];
addHero(name: string) {
this.heroes.push({name});
// After this code runs I expected the input to be empty
this.name = '';
}
}
You have one-way binding so when you're typing something in your input your name property isn't changed. It remains "". After clicking on Add hero! button you doesn't change it.
addHero(name: string) {
this.heroes.push({name}); // this.name at this line equals ''
this.name = ''; // it doesn't do any effect
}
Angular2 will update value property only if it is changed.
Use two-way binding which is provided by #angular/forms
[(ngModel)]="name"
to ensure that your name property will be changed after typing.
Another way is manually implementing changing
[value]="name" (change)="name = $event.target.value"
In Angular Template binding works with properties and events, not attributes. as per html attribute vs dom property documentation of angular so as you have used [value] binding its binding to attributes not to the property of that input and because of it value remain in it after you set this.name = "".

Categories

Resources