我有这样的父组件
<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>
子组件
<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>
你能帮助我在父组件中获取子表单值,单击父组件中的下一步按钮。
答案 0 :(得分:1)
使用服务..在服务中有一些getter和setter,并在父组件中注入服务,设置值并在子组件中注入服务并获取值并将它们分配给某些变量并将它们绑定在模板中。这是服务的例子
import { Injectable } from '@angular/core';
@Injectable()
export class ActiveclassService {
constructor() { }
private rolesclass:any;
setrolesclass(rolesclass){
this.rolesclass=rolesclass;
}
getrolesclass(){
return this.rolesclass;
}
答案 1 :(得分:0)
家长侦听子事件
子组件公开一个EventEmitter属性,当事情发生时,它会使用该属性发出事件。父级绑定到该事件属性并对这些事件做出反应。
子级的EventEmitter属性是一个输出属性,通常使用@Output装饰进行装饰,如 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;
}
}
单击按钮会触发布尔有效载荷的真或假发射。
父VoteTakerComponent绑定一个名为onVoted()的事件处理程序,它响应子事件有效负载$ event并更新计数器。 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