Invalid event target - when using fromEvent with Angular Material Button - javascript

I am trying to setup a click event to a Button dynamically using fromEvent and defer modules of rxjs.
It works fine when using normal html button, but doesn't work with Angular Material button.
Here is the code works fine with Normal Button:
import { Component, OnInit, ViewChild, ElementRef } from '#angular/core';
import { defer, fromEvent } from 'rxjs';
import { map, tap } from 'rxjs/operators';
#Component({
selector: 'app-test',
template: `
<button #testBtn>Click me</button>
`
})
export class TestComponent implements OnInit {
#ViewChild('testBtn', { static: true }) testBtn: ElementRef<HTMLButtonElement>;
event$ = defer(() => fromEvent(this.testBtn.nativeElement, 'click')).pipe(
map(() => new Date().toString()),
tap(console.log)
)
constructor() { }
ngOnInit() {
this.event$.subscribe();
}
}
And here is the code which doesn't work with Angular Material Button
import { Component, OnInit, ViewChild, ElementRef } from '#angular/core';
import { defer, fromEvent } from 'rxjs';
import { map, tap } from 'rxjs/operators';
#Component({
selector: 'app-test',
template: `
<button mat-raised-button #testBtn>Click me</button>
`
})
export class TestComponent implements OnInit {
#ViewChild('testBtn', { static: true }) testBtn: ElementRef<HTMLButtonElement>;
event$ = defer(() => fromEvent(this.testBtn.nativeElement, 'click')).pipe(
map(() => new Date().toString()),
tap(console.log)
)
constructor() { }
ngOnInit() {
this.event$.subscribe();
}
}
I couldn't guess why this problem is happening.
Can you help me understand it ?

EDIT: add it { read: ElementRef } your ViewChild;
Use it for your matButton.
#ViewChild("myButton", { read: ElementRef }) myButtonRef: ElementRef;
You need to use your button as nativeElement ElementRef;

Related

Angular eventemitter not working when emitting the event from directive

appcomp.html
`<app-child (callemit) = parentFunc($event)> </app-child>`
appcomp.ts
`
import { Component, OnInit, EventEmitter } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.comp.html'
})
export class AppComponent {
ngOnInit() {}
parentFunc(event){
console.log(event)
}
}
`
childcomp.html
childcomp.ts
`
#Component({
selector: 'app-child',
templateUrl: './app.child.component.html'
})
`
mydirective.ts
`
import { Directive, ElementRef, Input, Output, HostListener, EventEmitter } from '#angular/core';
#Directive({
selector: '[myDirective]'
})
export class myAppDirective {
constructor() {}
#Input ('myDirective') val: string;
#Output() callEmit = new EventEmitter();
#HostListener('click')
onClick() {
event.preventDefault();
this.callEmit.emit({event , val});
}
}
`
In the above code i am trying to call parentFunc from appcomp using eventemitter and not able to get this work. Please let me know what is wrong here.
I think you most call callEmit on child component
childcomp.html
and in child Component emit the CallEmit Which called from appComp
childcomp.ts
#Output() callEmit = new EventEmitter();
childFunc(){
this.callEmit.emit();
}
and finally use
appCom.html
`<app-child (callemit) = parentFunc($event)> </app-child>`
appcom.ts
parentFunc(event){
console.log(event)
}
https://stackblitz.com/edit/angular-exxhms
Try it on component

#Output childEvent not initialized

I am fairly new to the Angular world and working on angular 7, I am doing some examples where components share data within, The Parent to child part working fine but when i am trying to send any values from child to parent it's not working.
It shows me this error
app-component.html
<div>{{show}}</div>
<app-communicating-components [Parent]="message" (childEvent)="getMessage($event)"></app-communicating-components>
app-component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'AngularLesson2';
public message = 'Hello my child, Parents here';
public show: string;
getMessage($event) {
this.show = $event;
}
}
communicating-components.component.html
<p>
{{Parent}}
</p>
<button (click)="fireEvent()">Fire from child</button>
communicating-components.component.ts
import { Component, OnInit, Input, Output } from '#angular/core';
import { EventEmitter } from 'events';
#Component({
selector: 'app-communicating-components',
templateUrl: './communicating-components.component.html',
styleUrls: ['./communicating-components.component.css']
})
export class CommunicatingComponentsComponent implements OnInit {
#Input() Parent;
#Output() public childEvent = new EventEmitter();
constructor() {
}
ngOnInit() {
}
fireEvent() {
this.childEvent.emit('Hi, I am child');
console.log("event fire" + this.childEvent);
}
}
What am I doing wrong here?
I believe the problem is in your import import { EventEmitter } from 'events'; is not the one you should import here. Try changing the import to import { EventEmitter } from '#angular/core';
UPDATE
Here's a stackblitz example showing that it works
With Angular newer versions, like 8 you have to:
Import correctly Emitter as k.s. said:
import { EventEmitter } from '#angular/core'
Initialize the emitter for Output:
#Output()
emisor = new EventEmitter<type>();

Angular 5 BehaviorSubject not working for boolean value

I am trying to practice behaviorsubject in angular 5. I am written a small app with two components and want to change the value in both of them at once but the value is not changing. BehaviorSubject should change the value in all the components. Please help me understand.
Service
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class TestserviceService {
public isAdmin = new BehaviorSubject<boolean>(false);
cast = this.isAdmin.asObservable();
constructor() { }
changeAdmin(){
this.isAdmin.next(!this.isAdmin);
}
}
Component One
import { Component, OnInit } from '#angular/core';
import{ TestserviceService } from '../../testservice.service';
#Component({
selector: 'app-one',
templateUrl: './one.component.html',
styleUrls: ['./one.component.css']
})
export class OneComponent implements OnInit {
isAdmin: boolean;
constructor(private testservice: TestserviceService) { }
ngOnInit() {
this.testservice.cast.subscribe(data => this.isAdmin = data);
}
changeValue(){
this.testservice.changeAdmin();
console.log(this.isAdmin);
}
}
Component One html
<button (click)="changeValue()">Click Me</button>
<p>
one {{isAdmin}}
</p>
Component Two
import { Component, OnInit } from '#angular/core';
import { TestserviceService } from '../../testservice.service';
#Component({
selector: 'app-two',
templateUrl: './two.component.html',
styleUrls: ['./two.component.css']
})
export class TwoComponent implements OnInit {
isAdmin: boolean;
constructor(private testservice: TestserviceService) { }
ngOnInit() {
this.testservice.cast.subscribe(data => this.isAdmin = data);
console.log("two "+this.isAdmin);
}
}
changeAdmin(){
this.isAdmin.next(!this.isAdmin);
}
Should be
changeAdmin(){
this.isAdmin.next(!this.isAdmin.value);
}
this.isAdmin is a BehaviorSubject and you were trying to set !thisAdmin which evaluates to false
Stackblitz
Change your service to :
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
#Injectable()
export class SharedServiceService {
constructor() { }
public isAdmin = new BehaviorSubject<boolean>(false);
cast = this.isAdmin.asObservable();
changeAdmin(){
this.isAdmin.next(!this.isAdmin.value);
}
}
It should be this.isAdmin.value because this.admin will only be behaviourSubject's object
Live Demo

ExpressionChangedAfterItHasBeenCheckedError . Angular 2(5) *ngIf

I'm using a service to pass data between child and parent with the purpose being to update the parent ui with child specific info depending on what child is loaded.
Service:
import { Subject } from "rxjs/Subject";
export class ChildDataService {
private childDetails = new Subject<{}>();
childLoaded$ = this.childDetails.asObservable();
changedComponentName(option: {}){
this.childDetails.next(option);
}
}
Parent Component:
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";
#Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
childDetails: {title?: string};
private subscription:Subscription;
constructor( private childDataService: ChildDataService) {
this.childDataService.childLoaded$.subscribe(
newChildDetails => {
console.log(newChildDetails);
this.childDetails = newChildDetails
});
}
}
Example Child Component:
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import { ChildDataService } from "../../core/helpers/child-data.service";
#Component({
selector: 'app-child-dashboard',
templateUrl: './child-dashboard.component.html',
styleUrls: ['./child-dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ChildDashboardComponent implements OnInit {
constructor(private childDataService: ChildDataService) { }
public ngOnInit() {
this.childDataService.changedComponentName({
title: 'Dashboard'
});
}
}
Parent HTML:
<div class="subheader">
<h1>{{ childDetails?.title }}</h1>
<button *ngIf="childDetails?.title == 'Dashboard'">dashboard</button>
<button *ngIf="childDetails?.title == 'SecondChild'">Second Child</button>
</div>
With this setup I am getting the error "ExpressionChangedAfterItHasBeenCheckedError" when i click on a routerLink, now if i click on the same link a second time, the error persists but the correct button becomes visible. Spent all weekend getting nowhere with this, so any help would be greatly appreciated.
public ngOnInit() {
setTimeout(() => {
this.childDataService.changedComponentName({
title: 'Dashboard'
}), {});
}
it should work.
async ngOnInit() {
await this.childDataService.changedComponentName({
title: 'Dashboard'
});
}

implement angular2-virtual-scroll with observable in angular4

I am trying to implement angular2-virtual-scroll in an angular4 project. Firstly, can anyone confirm if I would have a problem implementing it in NG4. I don't think I should and I haven't seen any notices to the contrary. Secondly I am using an observable instead of a promise shown in the NPM angular2-virtual-scroll docs. However, when I applied the virtual-scroll tag there is no change in my output...no scroll bar ..the data from the observable is displayed but no scrolling. The following are the relevant code segments:
Home.component.html
<h1 style="color: #76323f">
{{title}}
</h1>
<h4>
{{description}}
</h4>
<h2>Coming Soon....</h2>
<app-events-list [upcomingEvents]="upcomingEvents"></app-events-list>
home.component.ts
import {Component, OnInit,OnDestroy } from '#angular/core';
import {UpcomingEvent} from './../../interface/upcomingevent';
import {EventService} from './../../services/event.service';
import {Subscription} from 'rxjs/Subscription';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
upcomingEvents: Array<UpcomingEvent>;
title = 'Welcome....';
description='Events promotions....';
eventServiceSub: Subscription;
constructor(private eventService: EventService){
this.upcomingEvents = [];
}
ngOnInit() {
this.eventServiceSub=this.eventService.getEvents().subscribe(upcomingEvents=>{this.upcomingEvents=upcomingEvents.slice(0,25);
});
}
ngOnDestroy(){
if (this.eventServiceSub){
this.eventServiceSub.unsubscribe();
}
}
}
event-list-component.html
<virtual-scroll [items]="items" (update)="upcomingEvents = $event"
(change)="onlistChange($event)">
<app-upcomingevent *ngFor="let upcomingEvent of upcomingEvents"[upcomingEvent]="upcomingEvent" [eventItemCss]="'event-item'"></app-upcomingevent>
<div *ngIf="loading" class="loader">Loading.....</div>
</virtual-scroll>
event-list-component.ts
import { Component, Input, OnDestroy, OnInit } from '#angular/core';
import { UpcomingEvent } from './../../interface/upcomingevent';
import { trigger,state,style,transition,animate,keyframes } from '#angular/animations';
import { ChangeEvent } from 'angular2-virtual-scroll';
import {EventService} from './../../services/event.service';
import {Subscription} from 'rxjs/Subscription';
#Component({
selector: 'app-events-list',
templateUrl: './events-list.component.html',
styleUrls: ['./events-list.component.css'],
animations: []
})
export class EventsListComponent implements OnInit, OnDestroy {
#Input()
upcomingEvents: Array<UpcomingEvent>;
items=this.upcomingEvents;
protected buffer: Array<UpcomingEvent> =[];
protected loading: boolean;
eventServiceSub: Subscription;
constructor(private eventService: EventService) {
this.upcomingEvents=[];
}
ngOnInit() {
}
ngOnDestroy(){
if (this.eventServiceSub){
this.eventServiceSub.unsubscribe();
}
}
protected onlistChange(event: ChangeEvent){
if (event.end !==this.buffer.length) return;
this.loading=true;
this.eventServiceSub=this.eventService.getEvents().subscribe(upcomingEvents=>{
this.buffer=upcomingEvents.slice(this.buffer.length,25);
this.loading=false;
}, ()=> this.loading=false);
}
}
eventService.ts
import { Injectable } from '#angular/core';
import {UpcomingEvent} from './../interface/upcomingevent'
import {Http} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class EventService {
constructor(private http: Http) { }
getEvents(): Observable<UpcomingEvent[]>
{
return this.http
.get(`https://jsonplaceholder.typicode.com/posts`)
.map(response => response.json() as UpcomingEvent[]);
}
}
upcomingEvents.html
<md-card [ngClass]="'event-item'">
<h4 [ngClass]="'event-title'" [ngStyle]="{'color':'purple'}"> {{upcomingEvent.title}}</h4>
<md-card-actions>
<button md-button>LIKE</button>
<button md-button>SHARE</button>
</md-card-actions>
</md-card>
upcomingEvents.component.ts
import { Component, Input,OnInit } from '#angular/core';
import { UpcomingEvent } from './../../interface/upcomingevent';
#Component({
selector: 'app-upcomingevent',
templateUrl: './upcomingevent.component.html',
styleUrls: ['./upcomingevent.component.css']
})
export class UpcomingeventComponent implements OnInit {
#Input()
upcomingEvent: UpcomingEvent;
#Input()
eventItemCss: string;
constructor() { }
ngOnInit() {
if (!this.upcomingEvent) {
this.upcomingEvent=<UpcomingEvent> {};
}
}
}
The way it suppose to work is that the HomeComponent request data from the eventService via an observable..the data is then passed to the eventList component where it is iterated on and pass to the upcomingEvents component to present via HTML. 25 events are requested at first and if the user scroll to the end another 25 is requested from the eventService...this time by the upcomingEvents component. I am not sure this is the most efficient way to do it but in either case it doesn't work. The virtual-scroll seems to have no effect on the output....I would really appreciate someone showing me what I am doing wrong....Thanks
I think I see a problem in your code. When using virtual-scroll you need to keep two arrays - one for all loaded data, and one for currently rendered items. Looks like you kinda mixed them up.
Let's call all-items-array as items and render-array - upcomingEvents
First chunk of items will be passed from the parent component, hence:
Home.component.html
...
<app-events-list [items]="upcomingEvents"></app-events-list>
event-list-component.html looks good
event-list-component.ts
import { Component, Input, OnDestroy, OnInit } from '#angular/core';
import { UpcomingEvent } from './../../interface/upcomingevent';
import { trigger,state,style,transition,animate,keyframes } from '#angular/animations';
import { ChangeEvent } from 'angular2-virtual-scroll';
import {EventService} from './../../services/event.service';
import {Subscription} from 'rxjs/Subscription';
#Component({
selector: 'app-events-list',
templateUrl: './events-list.component.html',
styleUrls: ['./events-list.component.css'],
animations: []
})
export class EventsListComponent implements OnInit, OnDestroy {
#Input()
items: Array<UpcomingEvent> = [];
upcomingEvents: Array<UpcomingEvent>;
protected loading: boolean;
eventServiceSub: Subscription;
constructor(private eventService: EventService) {
this.upcomingEvents=[];
}
ngOnInit() {
}
ngOnDestroy(){
if (this.eventServiceSub){
this.eventServiceSub.unsubscribe();
}
}
protected onlistChange(event: ChangeEvent){
if (event.end !==this.items.length) return;
this.loading=true;
this.eventServiceSub=this.eventService.getEvents().subscribe(upcomingEvents=>{
this.items=upcomingEvents.slice(0, this.items.length + 25);
this.loading=false;
}, ()=> this.loading=false);
}
}
warning! code not tested, I simply edited your code.

Categories