Angular modal not updates with component variable change - javascript

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.

Related

Get value from directive into component

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>

Angular FormArray causing Formcontrol in another form to be lost

I've got an Angular component which displays data from a FormArray but there is also another FormGroup which only becomes visible when a button is clicked.
When the component loads, if I click on the button to make the other form visible immediately then it works. However if I click on another button or one of the FormArray inputs first when I make the other form visible it will error with 'Cannot find control'. Clicking to close and then re-display the other form will then work correctly.
I've spent hours trying to track down what's going wrong and it only seems to be when there is an *ngFor to loop through the FormArray items. I've boiled it down to this example:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, FormArray } from '#angular/forms';
#Component({
selector: 'app-test-filter-component',
templateUrl: './test-filter-component.component.html',
styleUrls: ['./test-filter-component.component.scss']
})
export class TestFilterComponentComponent implements OnInit {
public testform: FormGroup;
public otherForm: FormGroup;
public otherFormVisible = false;
constructor() {}
get orders() {
return this.testform.get('orders') as FormArray;
}
anotherClick() {}
ngOnInit() {
this.testform = new FormGroup({
orders: new FormArray([])
});
this.otherForm = new FormGroup({
test: new FormControl('testvalue')
});
for(let idx = 0; idx < 50; idx++) {
this.orders.push(new FormGroup({id: new FormControl(idx), name: new FormControl('test')}));
}
}
}
<div *ngIf="otherFormVisible">
<form [formGroup]="otherForm">
<input formControlName="test">
</form>
</div>
<button class="btn btn-primary" (click)="otherFormVisible = !otherFormVisible">other form</button>
<button class="btn btn-primary" (click)="anotherClick()">Click here first</button>
<form [formGroup]="testform">
TEST CONTROL
<div formArrayName="orders" *ngFor="let order of orders.controls; let i = index">
<div [formGroupName]="i">
<input formControlName="id">
<input formControlName="name">
</div>
</div>
</form>
If you click straight on 'other form' it shows the other form correctly, but if you click on 'Click here first' or any of the other inputs first it will error saying:
ERROR Error: Cannot find control with name: 'test'
If anyone knows how to get this working properly it would save me from hours more frustration.
You can replace
<div *ngIf="otherFormVisible">
with
<div [hidden]="!otherFormVisible">
Agree with #Stratubas answer and thanks to him for pointing out issue.
This issue is not reproducible in chrome version is 79.0.3945.130 (Official Build) (64-bit).
But i tried the same issue in stackblitz link given by #PierreDuc, in Microsoft Edge, that had Version 80.0.361.48 (Official build) (64-bit), This issue was reproducible here. This browser is Microsoft's Chromium-based browser.
I hope this will be helpful for anyone in future.
While the accepted answer did fix the small example I posted, the problem quickly reappeared when my forms got more complex.
After some further searching I discovered it is in fact a bug with Chrome 80+
https://github.com/angular/angular/issues/35214
And there is a workaround which fixed my problems here:
https://github.com/angular/angular/issues/35219#issuecomment-583425191

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