I would define an output into your State
component and triggers an event using it:
@Component({
selector: 'state',
providers: [FormBuilder],
templateUrl: 'app/state.html',
directives: []
})
export class State {
statesDropDownValues = ['NJ', 'NY', 'PA', 'CA'];
stateForm: ControlGroup;
@Output()
stateChange:EventEmitter<string> = new EventEmitter(); // <----
constructor(fb: FormBuilder) {
this.stateForm = fb.group({
'state': ''
});
}
setStateValue() {
alert('State Selected: ' + this.stateForm.value.state);
stateChange.emit(this.stateForm.value.state);
}
}
The parent component can register on this event to be notified of changes:
<div>
<h2>Registration Form</h2>
<form [ngFormModel]=registrationForm (ngSubmit)="onSubmit()">
<label>Name: </label>
<input type="text" ngControl="name">
<state (stateChange)="handleNewState($event)"></state>
<button [disabled]="!registrationForm.valid">Submit</button>
</form>
</div>
$event
contains the value of the new state value.
Edit
Here is a way to save the selected state in the parent component:
export class App {
registrationForm: ControlGroup;
state: string;
constructor(fb: FormBuilder) {
this.registrationForm = fb.group({
'name': ['', Validators.required],
'email': ''
});
}
handleNewState(state) {
this.state = state;
}
onSubmit() {
alert('Entered Name: ' + this.registrationForm.value.name);
alert('State Selected: ' + this.state);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…