Reputation: 5316
I have a parent component like this
<div>
<div class="selection-area active" style="max-height:initial;" contact-details [(contactDetailsD)]="conDetailsUI"></div>
</div>
<div>
<a href="javascript:void(0)" class="btn btn-dark btn--full" (click)="submitData()">Next</a>
</div>
The child component
<div>
<form>
<input type="text" name="name" value="{{contactDetailsD?.firstName}}">
<input type="text" name="email" value="{{contactDetailsD?.email}}">
<input type="text" name="phone" value="{{contactDetailsD?.phone}}">
</form>
</div>
Can you help me to get the child form values in parent component, onclick of Next button that present in the parent component.
Upvotes: 0
Views: 1125
Reputation: 792
Parent listens for child event
The child component exposes an EventEmitter property with which it emits events when something happens. The parent binds to that event property and reacts to those events.
The child's EventEmitter property is an output property, typically adorned with an @Output decoration as seen in this VoterComponent:
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'my-voter',
template: `
<h4>{{name}}</h4>
<button (click)="vote(true)" [disabled]="voted">Agree</button>
<button (click)="vote(false)" [disabled]="voted">Disagree</button>
`
})
export class VoterComponent {
@Input() name: string;
@Output() onVoted = new EventEmitter<boolean>();
voted = false;
vote(agreed: boolean) {
this.onVoted.emit(agreed);
this.voted = true;
}
}
Clicking a button triggers emission of a true or false, the boolean payload.
The parent VoteTakerComponent binds an event handler called onVoted() that responds to the child event payload $event and updates a counter. VoterParentComponet:
import { Component } from '@angular/core';
@Component({
selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of voters"
[name]="voter"
(onVoted)="onVoted($event)">
</my-voter>
`
})
export class VoteTakerComponent {
agreed = 0;
disagreed = 0;
voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
onVoted(agreed: boolean) {
agreed ? this.agreed++ : this.disagreed++;
}
}
SRC: https://angular.io/guide/component-interaction#parent-listens-for-child-event
Upvotes: 0
Reputation: 414
Use services.. Have some getters and setters in the services and inject the service in the parent component set the values and inject the service in the child component and get the values and assign them to some variables and bind them in the template. Here is the example of service
import { Injectable } from '@angular/core';
@Injectable()
export class ActiveclassService {
constructor() { }
private rolesclass:any;
setrolesclass(rolesclass){
this.rolesclass=rolesclass;
}
getrolesclass(){
return this.rolesclass;
}
Upvotes: 1