I have a mane page that have a button that triggers a pop up box to appear:
<i class="material-icons" (click)="openPopUp()">info</i>
openPopUp() is just setting the property to true:
openPopUp() {
this.showPopup = true;
}
and then im sending the value of showPopUp to the PopupComponent(its separate component):
<div *ngIf="showPopup === true">
<pop-up-info-box [componentBPopUp]="showPopup"></pop-up-info-box>
</div>
but now in the componenetB i have the closePopUp func that is triggered from the html:
close
and is just setting the componentBPopUp to be false:
#Input
public componentBPopUp: boolean;
public closePopUp() {
this.popUp = false;
}
but what actually need to be set to false is the showPopup in the first component...how do I set its value properly?
thanks
You should use #Output in componentBPopUp.
for example:
close(){
this.showPopup = false;
}
Example of what you trying to do:
https://plnkr.co/edit/kUWrlnoXgJ15rXObdaqh?p=preview
Good Luck!!!
What you should do in ComponentB is to raise an event on close.
#Output() onClose: EventEmitter<boolean> = new EventEmitter();
public closePopUp() {
this.onClose.emit(true);
}
Now on the parent just subscribe to this event:
<div *ngIf="showPopup === true">
<pop-up-info-box [componentBPopUp]="showPopup" (onClose)="showPopup = false">
</pop-up-info-box>
</div>
To your question a parent component can refer to a child component using the #ViewChild decorator
#ViewChild('popup')
popup: ModalComponent;
this.popup.doStuff();
<div *ngIf="showPopup === true">
<pop-up-info-box #popup [componentBPopUp]="showPopup"></pop-up-info-box>
</div>
But your specific problem can be solved with two-way data binding between the componentBPopUp and the showPopup field (see here)
Another option is to use EventEmmiter to notify the other component of the change (see here)
Related
I would like to know how to eliminate the mouseOver event from the template by using $ref. I want to control mouseOver behavior inside javascript instead.
Components component has myStats child component. myStats is supposed to be displayed only when I hover over Components.
I am not sure how make ref do what the commented out template code does.
Do I have to use a function of myStats (= onMouseEvent)? It would be easier if I can control mouseOver only inside Components
Components code:
<template>
<div class="pv-lookup" ref="myStats">
<!-- I would like to get rid of the commented out mouse hover event code below by using $ref: -->
<!-- <div #mouseover="mouseOver = true" #mouseout="mouseOver = false"> -->
<div>
<someComponent1 />
<someComponent2 />
<myStats v-if="mouseOver" #mouseMoved="onMouseMoved"/>
</div>
</div>
</template>
<script>
export default class Components extends Vue {
public mouseOver = false;
#Emit()
public onMouseMoved() {
this.mouseOver = !this.mouseOver;
}
mounted() {
this.$nextTick(() => {
if (this.isInhouseClient || this.isInhouse) {
// TODO: set value for this.mouseOver
// Approach 1:
// ERROR: Property 'onMouseEvent' does not exist on type 'Vue | Element | Vue[] | Element[]'.
this.$refs.myStats.onMouseEvent();
// Approach 2:
// ERROR: Property 'onMouseEvent' does not exist on type 'MouseEvent'. Did you mean 'initMouseEvent'?
const myStats= this.$refs.myStatsas HTMLElement;
myStats.addEventListener("mouseover", function( event ) {
event.onMouseEvent();
}, false);
// Approach 3:
// It's the simplest, but how do I connect with 'ref'?
this.mouseOver = !this.mouseOver;
}
});
}
}
</script>
myStats code:
<script>
export default class myStats extends Vue {
public mouseOver: boolean = false;
#Emit()
public mouseMoved(){}
public onMouseEvent() {
this.mouseMoved();
}
}
</script>
Thank you for your insights
You can simply add event listeners for the same events (mouseover and mouseout) to the DOM element. Beware though, these events bubble up from children. In your case it would be better to use mouseenter and mouseleave.
So your code will be:
mounted() {
const myStatsEl = this.$refs.myStats; // get DOM element of the component Components
myStatsEl.addEventListener("mouseenter", (event) => {
this.mouseOver = true;
});
myStatsEl.addEventListener("mouseleave", (event) => {
this.mouseOver = false;
});
},
No need to emit events from myStats component or use its functions.
That being said, the correct 'Vue-way' of doing this would be with #mouseenter and #mouseleave, which is much cleaner. I'm not sure why you wouldn't want to use that. I can't think of any cases where this way might be limiting.
In my application, there is a parent Product page component consists of two child components. The basic structure is like
Parent(ProductPage)
<template>
....
<div><ProductListTable /></div>
<div><EditActionComponent /></div>
....
</template>
In EditActionComponent, one edit button is there. ProductListTable is having products list where on each row click one edit modal will open.
So i want when i click edit button in edit action component then only row click will be enabled in product list table component.
EditActionComponent
methods:{
onEditAction(){
this.editable = true;
this.actionButtonsToShow = false;
this.editTextToshow = true;
this.$emit('editable',this.editable)
}
}
ProductListTable
methods: {
onRowClick() {
if(this.editable) { // i need this boolean value here
// modal open logic
}
}
}
So how to pass boolean value one child component to other child component?
since you're already emitting an event from your EditActionComponent you can get the boolean value by adding event listener for editable
eg: <EditActionComponent v-on:editable="callbackFunction">
in your ProductPage component, you create the callbackFunction(val) method to get the boolean value and store it in your data.
// ProductPage Component
data: () => ({
editable: false
}),
methods: {
callbackFunction(val) {
this.editable = val;
}
}
then you bind the variable to your ProductListTable component (assuming you have the editable props declared).
<ProductListTable :editable="editable" />
A button is only doing the function once, the video shows the problem:
https://vimeo.com/342491616
The logic goes like this:
When 'home' (inside footer.component) is clicked, sends function to parent(app.component), and then this one sends it to 'hamburguer' button (inside header.component).
I've read it may be something related to ngOnChanges but I tried it several times with it and it didn't work, but maybe I was using it wrong(?)
Code here:
footer.component.html
<a (click)="sendMessage()" routerLink="/page"><img src="assets/images/homebutton.png" class="footer_buttons" id="home_button"></a>
footer.component.ts (inside export class...)
message: string = "hamburguer";
#Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit(this.message);
//console.log(this.message);
}
/////////////////////////////////////////////////////////////
app.component.ts (inside export class...)
message = "";
receiveMessage($event){
this.message = $event;
//console.log($event);
}
/////////////////////////////////////////////////////////////
header.component.html
<div class="hamburguer">
<a (click)="getUrl();">
<img src="assets/images/{{ message }}.png" id="hamburguer">
</a>
</div>
header.component.ts (inside export class...)
#Input() message;
ngOnInit() {
if(window.location.pathname != "/settings"){
this.message = 'hamburguer';
}else{
this.message = 'cross';
}
}
This is happening because you fire the event only once.You need to remove the ngOninit Function and use your own function instead. Take a look at the following StackBlitz example
By the way,You rather work with variables instead working with the URL.URL is dynamic and could change, Pass a variable into your function and populate this.message according to that.
ngOnInit is a function that active on the first time, and invoked once.
you should add another "if" statement in the footer button, Home Button, in order to change the "message" variable.
In my application I have a global search field which is used to filter the data in the list , list will have multiple column. From other component setting the filter value (setting to input value) it's happening but I have to trigger the manual keyboard event (enter key) action on the input.
I tried with viewChild decorator.
component.html
<input #gb type="text" placeholder="Global search.." class="changeListComponent_inputSearch" [(ngModel)]="jiraRef" />
component.ts
#ViewChild('gb') gb:ElementRef;
this.jiraRef = jiraRef;
const event = new KeyboardEvent("keypress",{ "which ": "13"});
this.gb.nativeElement.focus();
this.gb.nativeElement.dispatchEvent(event);
using this I could set the value and make a focus but keyboard event is not triggering.
Triggered the key up event using the native js code.
Placed the id attribute to the input element along with element reference.
Created the new function from inside my component.
triggerEvent(el, type) {
if ('createEvent' in document) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
var el=document.getElementById('gb-search');
this.triggerEvent(el,'keyup');
I'm not sure why you are making it complicated. why not just add a keypress event to the input field, and then also be able trigger that event through a viewChild?
<input id="text1" type=text (keyup)="enterPressed()">
and then also be able to access this same method through a view child:
this.viewChild.enterPressed();
In general your inputs can be like:
<input (keydown.enter)="doEnter()">
From other component simply call to the function doEnter. How?
If the search component is in the parent it's easy because you can use ViewChild
<search-component></search-component>
#ViewChild(SearchComponent) searchComponent
..whe we need..
this.searchComponent.doEnter()
Else, typical use a Subject to subscribe. You has a service,
#Injectable({
providedIn: 'root',
})
export class KeyBoardService {
keyboard:Subject<any>=new Subject<any>()
constructor() { }
}
In your component Search, inject the service in constructor and in ngOnInit
constructor(private keyboardService:KeyBoardService){}
ngOnInit(){
this.keyboardService.keyboard.subscribe(_=>{
this.doEnter()
})
}
And in the other component
constructor(private keyboardService:KeyBoardService){}
..in anywhere..
this.keyboardService.next(null);
Exist another option that is when the two components are at time in the screen -and in the same <router-outlet></router-outlet> that is use a template reference variable and a Input. So we has
<search-component #search></search-component>
<other-component [search]=search><other-component>
in other component
#Input('search') searchComponent
..in anywhere
this.searchComponent.doEnter
You can simply use
<input type=text (keypress)="eventHandler($event)">
eventHandler(event) {
console.log(event, event.keyCode, event.keyIdentifier);
}
Solution is based on this answer
Get which key pressed from (keypress) angular2
A Component's EventEmitter does fire in some cases but does not in other cases. Why?
I have a custom Date picker. You can change the date manually (<input>) or use ng2-bootstrap <datepicker> to select conveniently.
I have this template:
<input [(ngModel)]="dateString"
class="form-control"
(focus)="showPopup()"
(change)="inputChange()">
<datepicker class="popup" [ngClass]="{ 'popup-hidden': !showDatepicker }"
[(ngModel)]="dateModel"
[showWeeks]="true"
(ngModelChange)="hidePopup($event)">
</datepicker>
The component with the relevant parts:
export class CustomDatepickerComponent {
#Input()
dateModel: Date;
dateString: string;
showDatepicker = false;
#Output()
dateModelChange: EventEmitter<Date> = new EventEmitter();
showPopup() {
this.showDatepicker = true;
}
// Called when the date is changed manually
// It DOES fire the event
inputChange() {
let result = moment(this.dateString, 'YYYY-MM-DD');
this.update(result.toDate());
}
// Called through the DatePicker of ng-bootstrap
// It DOESN'T fire the event
// However, the showDatepicker binding takes effect (see template)
hidePopup(event: Date) {
showDatepicker = false;
this.update(event);
}
update(date: Date) {
this.dateModel = date;
this.dateString = moment(date).format('YYYY-MM-DD');
// This SHOULD fire the event
// It is called in BOTH cases!
// But it fires only when the date is changed through the <input>
this.dateModelChange.emit(this.dateModel);
}
I use this datepicker this way:
<custom-datepicker [dateModel]="testDate" (change)="change($event)"></custom-datepicker>
Here's the change() handler function.
testDate = new Date();
change($event) { console.info('CHANGE', $event); }
Any ideas?
Ok... Now this is somewhat embarassing.
This was the usage of this component:
custom-datepicker [dateModel]="testDate" (change)="change($event)"></custom-datepicker>
Which should be changed to:
custom-datepicker [dateModel]="testDate" (dateModelChange)="change($event)"></custom-datepicker>
The interesting part is that it seems that the changed event of the <input> element bubbled up from CustomDatepickerComponent. It was handled inside the component, it fired dateModelChange which was not handled, then it bubbled up to the outer component as change event -- and this way it was handled.
If I passed the event to inputChange() and called event.stopPropagation() then it was cancelled and did not propagate.
Once again: it was nothing to do with EventEmitter.
I had a similiar issue. I solved it by decoupling the #ainput date model (datemodel) from the date model used inside the datepicker ( localdate: Date;)
Then I used ngOnChange to keep these both variables synced. This way, the EventEmitter is working fine and sending a value for each date selection or update.
export class myDatepicker implements OnChanges{
localdate: Date;
#Input() datemodel: Date;
#Input() isOpen: boolean = false;
#Input() label: string;
#Input() disabled: boolean = false;
#Output() datemodelChange: EventEmitter<Date> = new EventEmitter<Date>();
// Date has been selected in Datepicker, emit event
public selectedDate(value: any) {
this.datemodelChange.emit(value);
}
// React on changes in the connected input property
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
try {
if (changes["datemodel"] && changes["datemodel"].currentValue) {
this.localdate = moment(changes["datemodel"].currentValue).toDate(); // raw Input value
}
} catch (ex) {
console.log('myDatePicker: ' + ex);
}
}
}
Another solution for anyone stumbling across this page.
I had a similar issue which was also not the fault of EventEmitter. :-)
Initially it appeared my EventEmitter was intermittently not firing, however the culprit turned out to be the click handler responsible for firing the EventEmitter.
I had this in my html template:
<button mat-mini-fab color="primary">
<i class="fas fa-pencil-alt" (click)="onClickEdit()"></i>
</button>
and the click handler:
export class MyClass {
#Output() edit = new EventEmitter();
constructor() { }
onClickEdit() {
console.log('onClickEdit(), this.edit=' + this.edit);
this.edit.emit();
}
}
I added the console.log() to debug the problem, and I noticed onClickEdit() was not fired every time I clicked the fancy edit icon, which explains why the EventEmitter wasn't firing. :-)
I fixed this by moving the (click) attribute to the enclosing button (in hindsight it seems kind of obvious.)
<button mat-mini-fab color="primary" (click)="onClickEdit()">
<i class="fas fa-pencil-alt"></i>
</button>
Problem solved.