I'm building a simple web based application using angular version 6.
In my application there is a component which has a child component. There is a function in this component(In the parent component, not the child component.) and I want to invoke that function using a button which is in the child component.
This image explains the format of my components.
I think its regarding to angular #Output. But i can't manage it.
This is how my code has organized.
Parent Component - component.ts file
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-teacher-home',
templateUrl: './teacher-home.component.html',
styleUrls: ['./teacher-home.component.scss']
})
export class TeacherHomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
formView: boolean = false;
toggleForm(){
this.formView = !this.formView;
}
}
Parent component - component.html file
<div>
<child-compnent></child-compnent>
</div>
Child component - component.html file
<div>
<button>Toggle Form view</button>
</div>
i want to callthe function toggleForm() of parent component when the button clicked which is in child component.
read this article: Understanding #Output and EventEmitter in Angular
child component:
#Component({
selector: 'app-child',
template: `<button (click)="sendToParent('hi')" >sendToParent</button> `
})
export class AppChildComponent {
#Output() childToParent = new EventEmitter;
sendToParent(name){
this.childToParent.emit(name);
}
}
parent component:
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
toggle(){
console.log('toggle')
}
}
parent html:
<app-child (childToParent)="toggle($event)"></app-child>
working DEMO
You have a couple of ways to do this :
Is to create an event inside the child component and then give it a callback, something like this:
#Output('eventName') buttonPressed = new EventEmitter();
and call buttonPressed.emit() when you want the event to be triggered
on the parent side it will look like this :
<div>
<child-compnent (eventName)="toggleForm()"></child-compnent>
</div>
Another way is to create a shared service that will contain the shared functions and data for both components
You need to use #Output decorator inside your child component and emit an event when the button present clicked inside your child.
For eg: -
Child component.html
<div>
<button (click)="childButtonClicked()">Toggle Form view</button>
</div>
Child component.ts
export class ChildComponent {
#Output triggerToggle: EventEmitter<any> = new EventEmitter<any>();
...
childButtonClicked() {
this.triggerToggle.emit(true);
}
...
}
Parent Component
<div>
<child-compnent (triggerToggle)="toggleForm()"></child-compnent>
</div>
You can use EventEmitter of angular to listen to events from your child component.
parent.component.ts
toggleForm($event) {}
parent.component.html
<div>
<child-compnent (trigger)="toggleForm($event)" ></child-compnent>
</div>
child.component.ts
#Output() trigger : EventEmitter<any> = new EventEmitter<any>();
buttonClick(){
this.trigger.emit('click');
}
Related
Is it possible to create a custom event in Angular, within same component?
I am trying to create a custom click event in "app.component.html" file:
<li (customClick) = "cClick($event)"> Test </li>
and then in the app.component.ts file:
cClick(e){ (alert("custom event clicked!"))}
How to achieve this calling within same component? Please help :)
footer component
#Component({
selector: 'a-footer',
template: `
<div>{{footerText}}</div>
<button ion-button (click)="doIt()">Footer Button</button>
`
})
export class AFooterComponent {
#Input() footerText:string
#Output() footerClicked = new EventEmitter()
doIt() {
this.footerClicked.emit({value:this.footerText})
}
}
home.page component create the event handler to be passed into footer component doFooterClicked
#Component({
selector: 'page-home',
templateUrl: 'app/home.page.html'
})
export class HomePage {
appName = 'Ionic App';
userCourse =[]
constructor(private navController: NavController) {
this.userCourse = [{CourseName:"course one"},{CourseName:"course two"}]
}
edit4(_someStuff) {
}
doFooterClicked(_event) {
console.log(_event)
alert("footer clicked "+ _event.value)
}
}
in the home.page html somewhere you create the component element
<a-footer [footerText]="'someText'"
(footerClicked)="doFooterClicked($event)">
</a-footer>`
<li (customClick) = "cClick($event)"> Test </li>
You have to create a directive, where you can listen to whatever event you want and trigger them in your custom output emitters
Angular2 Directive to modify click handling
THE PROBLEM
So I have two Angular components, a parent and a child. The parent passes a custom template to the child component, which then hydrates the template with its own data using ngTemplateOutlet.
This works well for the most part. Unfortunately, I run into issues when trying to access the DOM elements of this parent template from the child.
If I try to access <div #container></div> from the default child template using #ViewChild('container',{static: false}), it gets the element without issue. When I do the same using the custom template passed in by app.component, I get the error "cannot read property 'nativeElement' of undefined".
What else do I have to do to access the DOM of my template?
Here's a Stackblitz
App.Component (Parent)
import { Component } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {}
<child [customTemplate]="parentTemplate"></child>
<ng-template #parentTemplate let-context="context">
<div #container>HELLO FROM CONTAINER</div>
<button (click)="context.toggleShow()">Toggle Display</button>
<div *ngIf="context.canShow">Container contains the text: {{context.getContainerText()}}</div>
</ng-template>
child.component (Child)
import {
Component,
ElementRef,
Input,
TemplateRef,
ViewChild
} from "#angular/core";
#Component({
selector: "child",
templateUrl: "./child.component.html",
styleUrls: ["./child.component.css"]
})
export class ChildComponent {
#Input() public customTemplate!: TemplateRef<HTMLElement>;
#ViewChild("container", { static: false })
public readonly containerRef!: ElementRef;
templateContext = { context: this };
canShow: boolean = false;
toggleShow() {
this.canShow = !this.canShow;
}
getContainerText() {
return this.containerRef.nativeElement.textContent;
}
}
<ng-container *ngTemplateOutlet="customTemplate || defaultTemplate; context: templateContext">
</ng-container>
<ng-template #defaultTemplate>
<div #container>GOODBYE FROM CONTAINER</div>
<button (click)="toggleShow()">Toggle Display</button>
<div *ngIf="canShow">Container contains the text: {{getContainerText()}}</div>
</ng-template>
MY QUESTION
How do I use #ViewChild to access this div from an outside template that updates with any changes in the DOM? (Note: Removing the *ngIf is NOT an option for this project)
What's causing this? Are there any lifecycle methods that I can use to remedy this issue?
MY HUNCH
I'm guessing that ViewChild is being called BEFORE the DOM updates with its new template and I need to setup a listener for DOM changes. I tried this and failed so I'd really appreciate some wisdom on how best to proceed. Thanks in advance :)
EDIT:
This solution needs to properly display <div #container></div> regardless of whether you're passing in a custom template or using the default one.
ViewChild doesn't seem to pick up a rendered template - probably because it's not part of the components template initially. It's not a timing or lifecycle issue, it's just never available as a ViewChild
An approach that does work is to pass in the template as content to the child component, and access it using ContentChildren. You subscribe to the ContentChildren QueryList for changes, which will update when the DOM element becomes rendered
You can then access the nativeElement (the div). If you wanted you could add listeners here to the DOM element, and trigger cd.detectChanges afterwards, but that would be a bit unusual. It would probably be better to handle DOM changes in the parent element, and pass the required values down to the child using regular #Input on the child
#Component({
selector: "my-app",
template: `
<child>
<ng-template #parentTemplate let-context="context">
<div #container>Parent Template</div>
</ng-template>
</child>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent {}
#Component({
selector: "child",
template: `
<ng-container *ngTemplateOutlet="customTemplate"> </ng-container>
`,
styleUrls: ["./child.component.css"]
})
export class ChildComponent implements AfterContentInit {
#ContentChild("parentTemplate")
customTemplate: TemplateRef<any>;
#ContentChildren("container")
containerList: QueryList<HTMLElement>;
ngAfterContentInit() {
this.containerList.changes.subscribe(list => {
console.log(list.first.nativeElement.innerText);
// prints 'Parent Template'
});
}
}
I need to pass input's value from child component to parent component when user click on a submit button that exists in parent component.
childComp template
<input
type="password"
[(ngModel)]="userPasswordForm.inputId"
class="mr-password-field k-textbox"
/>
childComp TS file
export class PasswordInputComponent{
constructor() { }
#Output() inputValue = new EventEmitter<string>();
userPasswordForm:any={'input':''};
emitValue(value: string) {
this.inputValue.emit(value);
}
}
Parent Component Template
<child-component (inputValue)="" > </child-component>
<button (click)="getValueFromChild()"> </button>
Parent Component TS file
tempUserFormPasswords:any=[];
.
.
.
getValueFromChild(receivedVal){
this.tempUserFormPasswords.push(receivedVal);
}
It would easy to dio it if the button exists inside the child component. but in this case the value should be passed when the button in the parent component is clicked!
For single ChildComponent:
Use ViewChild
For multiple ChildComponent use: ViewChildren
Parent Component TS file
Single Child Component:
tempUserFormPasswords:any=[];
#ViewChild(ChildComponent) child: ChildComponent;
.
.
.
getValueFromChild(receivedVal){
var data = child.getData();
this.tempUserFormPasswords.push(data);
}
Multiple Child Component:
tempUserFormPasswords:any=[];
#ViewChildren(ChildComponent) child: ChildComponent;
#ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
.
.
.
getValueFromChild(receivedVal){
let data;
children.forEach(child => (data = this.updateData(child.data));
this.tempUserFormPasswords.push(data);
}
Create a BehaviorSubject in service file
#Injectable()
export class dataService {
data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
public setData(data: any){
this.data.next(data);
}
public getData(): Observable<any> {
return this.data.asObservable();
}
}
You need to subscribe the data in your child component
PasswordInputComponent
export class PasswordInputComponent{
constructor(private service: dataService) {
this.service.getData().subscribe((data) => {
//Emit the event here
this.inputValue.emit(value);
});
}
#Output() inputValue = new EventEmitter<string>();
userPasswordForm:any={'input':''};
emitValue(value: string) {
this.inputValue.emit(value);
}
}
ParentComponent.ts
tempUserFormPasswords:any=[];
.
.
.
constructor(private service: dataService) { }
getValueFromChild(receivedVal){
this.service.setData('');
this.tempUserFormPasswords.push(receivedVal);
}
When a button clicked on the parent component we are setting the data behaviour subject, when a new value added to that it will automatically subscribed in child component.so, on that time we need to emit a event.
I think this will help you..
Read about Input and Output decorators in angular!
documentation: sharing-data.
Examples: examples
You can do it with ViewChild as already said in the other answer from #Raz Ronen. But keep in mind that depending on the Angular version, you might need to wait for the AfterViewInit lifecycle hook to be executed to interact with the child (or the child won't be available since it's not initialized).
Also, you can do it with a BehaviorSubject, like #Msk Satheesh just answered, and it's perfectly fine too. But it might be considered a bit overkill for such a simple use case.
(this is what we usually do when we don't have a relation between the components e.g one component is not children of the other one)
What I suggest is I think the simplest of all (again, their answers are not bad by any means);
It is basically the same of #Msk Satheesh (but under the hood), just a bit more Angular styled: Output + EventEmitter:
Parent component:
import { Component } from '#angular/core';
#Component({
selector: 'app-parent',
template: `
Message: {{message}}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
Children Component:
import { Component, Output, EventEmitter } from '#angular/core';
#Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "a string from child component"
#Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
With the code, the parent will always be subscribed to the messageEvent that’s outputted by the child component, and it will run the function (the message function) after the child emits. Handling this with Angular has the advantage that we are sure that we don't have any memory leak in our app (e.g missing unsubscriptions).
When the component that is listening (the subscribed parent) gets destroyed, Angular will unsubscribe automatically to avoid potential memory leaks.
Trying to do child to parent communication with #Output event emitter but is no working
here is the child component
import { Component, OnInit, Output, Input, EventEmitter } from '#angular/core';
#Component({
selector: 'app-emiter',
templateUrl: './emiter.component.html',
styleUrls: ['./emiter.component.css']
})
export class EmiterComponent implements OnInit {
#Output() emitor: EventEmitter<any>
constructor() { this.emitor = new EventEmitter()}
touchHere(){this.emitor.emit('Should Work');
console.log('<><><><>',this.emitor) // this comes empty
}
ngOnInit() {
}
}
this is the html template
<p>
<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button>
</p>
The console.log inside the touchHere it shows nothing
even if I put this inside the parent component it show nothing as well
parent component
import { Component , OnInit} from '#angular/core';
// service I use for other stuff//
import { SenderService } from './sender.service';
// I dont know if I have to import this but did it just in case
import { EmiterComponent } from './emiter/emiter.component'
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
user: any;
touchThis(message: string) {
console.log('Not working: ${message}');
}
constructor(private mySessionService: SenderService) { }
}
and here is the html template
<div>
<app-emiter>(touchHere)='touchThis($event)'</app-emiter>
</div>
Parent component template:
<app-emitor (emitor)='touchThis($event)'></app-emiter>
In parent template #Output should be 'called', not the child method.
Also, see: https://angular.io/guide/component-interaction#parent-listens-for-child-event
Here’s an example of how we write a component that has outputs:
#Component({
selector: 'single-component',
template: `<button (click)="liked()">Like it?</button>`
})
class SingleComponent {
#Output() putRingOnIt: EventEmitter<string>;
constructor() {
this.putRingOnIt = new EventEmitter();
}
liked(): void {
this.putRingOnIt.emit("oh oh oh");
}
}
Notice that we did all three steps: 1. specified outputs, 2. created an EventEmitter that we attached
to the output property putRingOnIt and 3. Emitted an event when liked is called.
If we wanted to use this output in a parent component we could do something like this:
#Component({
selector: 'club',
template: `
<div>
<single-component
(putRingOnIt)="ringWasPlaced($event)"
></single-component>
</div>`
})
class ClubComponent {
ringWasPlaced(message: string) { console.log(`Put your hands up: ${message}`);
} }
// logged -> "Put your hands up: oh oh oh"
Again, notice that:
putRingOnIt comes from the outputs of SingleComponent
ringWasPlaced is a function on the ClubComponent
$event contains the thing that wasemitted, in this case a string
<app-emiter (emitor)="touchThis($event)" ></app-emiter>
By using #Output() you should apply the event you need to emit in the directive of the emitter component.Adding the name of the variable to the the directive and but the emitted over function inside the quotation passing the $event.
touchHere() is the method from which you are binding some value to emit with your EventEmitter. And your EventEmitter is 'emitor'.
So your code will work if you simply do the below:
<app-emiter (emitor)='touchThis($event)'></app-emiter>
How to change the value of a variable or use a method in a parent component from a child component without using input and output
I try something like this but not working.
#Component({
selector: 'child',
template: `
<div>
<h2>{{name}}</h2>
<button (click) = "rename()" > Rename Parent </button>
</div>
`,
})
export class Child {
name:string;
constructor() {
this.name = 'child'
}
rename() {
App.name = 'Rename';
}
}
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<child> </child>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
example here
plunker example
Input and Output are just made for this. It is, according to the Angular2 Documentation, made for communication between parent and child components.
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
<child [name]="this.name" (nameChanged)="this.name = $event"> </child>
`,
})
export class App {
name:string;
constructor() {
this.name = 'Angular2'
}
}
#Component({
selector: 'child',
template: `
<div>
<h2>{{name}}</h2>
<button (click) = "rename()" > Rename Parent </button>
</div>
`,
})
export class Child {
#Input() name:string;
#Output() nameChanged: EventEmitter<string> = new EventEmitter<string>();
constructor() {
}
rename() {
this.nameChanged.emit('Renamed');
}
}
Alternatively you could inject a service into both parent and child component, which has some values that both parent and child can access and modify. But make sure to add that service to either only the parent component or only the AppModule, otherwise you would get 2 instances of your service.
That is #Output and #Input in Angular 2.
Docs: https://angular.io/docs/ts/latest/cookbook/component-communication.html
Another way that is Observable, Subject you can also inject data from a child component to root component or from a component to another component : See this video: https://www.youtube.com/watch?v=U2qJxfi7370&list=PLFaW_8zE4amNEdKZOJD3P_GeV3Hgva7RD&index=10