Get value from directive into component - javascript

I have a directive that is used on input fields on my form. I am trying to get the value from that directive in my TS file
Directive
#Directive({
selector: '[appOskInput]',
})
export class OskInputDirective implements OnInit {
private isBlurTrue: boolean = false;
#HostListener('focus')
private onFocus() {
console.log("focus");
this.isBlurTrue = false;
this.keyboard.fireKeyboardRequested(true);
this.subscribeToKeyboardEvents();
}
#HostListener("onBlur")
private onBlur() {
console.log("blur");
this.isBlurTrue = true;
this.keyboard.fireKeyboardRequested(false);
this.unsubscribeFromKeyboardEvents();
}
}
HTML
<cb-form [formGroup]="setupForm">
<form-input
appOskInput
(inputChanged)="onInputChanged($event,'accountNumber')"
[formStatus]="formStatus"
[parentFormGroup]="setupForm"
[data]="{formControlName: 'accountNumber', name: 'accountNumber'}">
</form-input>
</cb-form>
Essentially I want to use the isBlurTrue value in my TS file. Anyone knows how I can do this?

I figured it out
I just passed an output event in the directive
#Output() blurChanged = new EventEmitter();
Then emitted the value to it
this.blurChanged.emit(this.isBlurTrue);
In my HTML
I added
(blurChanged)="onBlurChanged($event)"
And in my TS I added
onBlurChanged(ev) {
console.log(ev)
}

You could also have a public function within your directive where exposes your private property, and then use it in your template html from a parent control like this:
Directive
...
private isBlurTrue: boolean = false;
getBlur(): boolean {
return this.isBlurTrue;
}
HTML
<div #myDirective="appOskInput">
...
<input (blur)="myDirective.getBlur()"/>
...
</div>

Related

how to set dynamic attribute in angular 7

In Html:
<input class="form-control"[(ngModel)]="value" #muInput/>
<button (click)="onSetAttribute()"> set</button>`
In this:
`#ViewChild('muInput') muInput: ElementRef; `
public seperator : string onSetAttribute() { if(this.seperator ) {
this.muInput.nativeElement.setAttribute('mask' , this.seperator); this.muInput.nativeElement.setAttribute('thousandSeparator' , ',');`
}}
I want to click on the button set a mask attribute to input this my code but is not working
You can do something like this :
<input class="form-control"[(ngModel)]="value" #muInput [attr.mask]="mask" />
<button (click)="changeMask()"> set</button>
In your component ts file, you should declare a class attribute mask, give it default value of w/e you want then:
changeMask() { this.mask = 'separator.2' // w/e value }
same thing for thousandSeparator attribute.
import { Renderer2 } from '#angular/core';
Use Renderer2 setattribute function
constructor ( private _renderer: Renderer2) { }
onSetAttribute() {
this._renderer.setAttribute(this.muInput.nativeElement,'mask' , 'separator.2');
this._renderer.setAttribute(this.muInput.nativeElement,'thousandSeparator' , ',');
}

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";
}
}

Getting Date Formatted and Printed to Screen in Angular 2 App

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.

Categories

Resources