我正在学习Angular 2,关于注入依赖关系和提供者,但我有一个疑问。我的应用程序有2个组件:TrainingComponent和ExerciseFormComponent。这个想法是1训练有N个练习。 Training组件有一个属性Exercises,它包含一系列练习,而ExerciseFormComponent有一个方法:submit(),它在创建一个新练习时被调用。接下来我想要submit()使用addExerecise(exercise:Exercise)将新练习添加到TrainingComponent,但我不知道如何传递它以引用它来调用它。
ExerciseFormComponent
import {Component} from 'angular2/core';
import {NgForm} from 'angular2/common';
import {Exercise} from './exercise';
import {TrainingComponent} from './training.component';
@Component({
selector: 'exercise-form',
templateUrl: 'app/exercise-form.component.html',
directives: [TrainingComponent]
})
export class ExerciseFormComponent {
model = new Exercise(6, 'hola', 10, 'hey', 11, 12);
active = true;
submitted = false;
constructor(private _trainingComponent: TrainingComponent) {}
onSubmit() {
this.submitted = true;
//This doesn't work!
this._trainingComponent.addExercise(this.model);
}
newExercise() {
this.model = new Exercise(7, '', 0, '', 0, 0);
this.active = false;
setTimeout(()=> this.active=true, 0);
}
// TODO: Remove this when we're done
get diagnostic() { return JSON.stringify(this.model); }
}
TrainingComponent
import {Component} from 'angular2/core';
import {Exercise} from './exercise';
import {ExerciseFormComponent} from './exercise-form.component';
import {ExerciseService} from './exercise.service';
@Component({
selector: 'app',
template:`
<h1>{{title}}</h1>
<h2>My Training</h2>
<button type="button" (click)="getExercises()">Shoot!</button>
<ul class="training">
<li *ngFor="#exercise of exercises">
<span class="badge">{{exercise.id}}</span> {{exercise.name}}
</li>
</ul>
<exercise-form></exercise-form>
`,
directives: [ExerciseFormComponent],
providers: [ExerciseService]
})
export class TrainingComponent {
public title = 'Training';
public exercises: Exercise[];
constructor(private _exerciseService: ExerciseService) { }
getExercises() {
this._exerciseService.getExercises().then(exercises => this.exercises = exercises);
}
// This method is who should be invoked from submit() in ExerciseFormComponent
addExercise(exercise: Exercise){
this.exercises.push(exercise);
}
}
答案 0 :(得分:2)
与输入和输出结合使用比在组件之间创建紧密耦合更好。
这样您就可以制作一个事件(使用@Output()
)
export class ExerciseFormComponent {
@Output() exerciseAdded:EventEmitter<Exercise> = new EventEmitter<Exercise>();
onSubmit() {
this.submitted = true;
//This doesn't work!
this.exerciseAdded.emit(this.model);
}
这样您就可以订阅事件并在事件发生时调用方法:
<exercise-form (exerciseAdded)="addExercise($event)"></exercise-form>