从 child 组件调用 parent 函数
Calling parent functions from child component
我有以下结构。
ParentComponent.ts
reset(offense) {
return this.http.post(...);
}
ParentComponent.html
<ion-list>
<swipable-offense-card
*ngFor="let offense of filteredOffenses"
[offense]="offense"
(onReset)="reset(offense)"
>
</swipable-offense-card>
</ion-list>
和child:
ChildComponent.ts
@Component({
selector: 'swipable-offense-card',
templateUrl: 'swipable-offense-card.html',
})
export class SwipableOffenseCard {
@Input() offense: Offense;
@Output() onReset: EventEmitter<any> = new EventEmitter();
reset() {
this.onReset.emit();
}
}
}
ChildComponent.html
<p>{{ offense.title }}</p>
<button (click)="reset()"></button>
现在,使用此结构,我在此处传递的攻击参数 (onReset)="reset(offense)"
被发送到 parent 组件。但是,我更喜欢这样做。
ChildComponent.ts
reset() {
this.onReset.emit({
...this.offense
});
}
但是这个不会发送任何参数给 parent 组件的重置方法。我如何在 Angular?
中做到这一点
您必须像这样在参数中添加 $event
// ParentComponent.html
<ion-list>
<swipable-offense-card
*ngFor="let offense of filteredOffenses"
[offense]="offense"
(onReset)="reset($event)"
>
</swipable-offense-card>
</ion-list>
我有以下结构。
ParentComponent.ts
reset(offense) {
return this.http.post(...);
}
ParentComponent.html
<ion-list>
<swipable-offense-card
*ngFor="let offense of filteredOffenses"
[offense]="offense"
(onReset)="reset(offense)"
>
</swipable-offense-card>
</ion-list>
和child: ChildComponent.ts
@Component({
selector: 'swipable-offense-card',
templateUrl: 'swipable-offense-card.html',
})
export class SwipableOffenseCard {
@Input() offense: Offense;
@Output() onReset: EventEmitter<any> = new EventEmitter();
reset() {
this.onReset.emit();
}
}
}
ChildComponent.html
<p>{{ offense.title }}</p>
<button (click)="reset()"></button>
现在,使用此结构,我在此处传递的攻击参数 (onReset)="reset(offense)"
被发送到 parent 组件。但是,我更喜欢这样做。
ChildComponent.ts
reset() {
this.onReset.emit({
...this.offense
});
}
但是这个不会发送任何参数给 parent 组件的重置方法。我如何在 Angular?
中做到这一点您必须像这样在参数中添加 $event
// ParentComponent.html
<ion-list>
<swipable-offense-card
*ngFor="let offense of filteredOffenses"
[offense]="offense"
(onReset)="reset($event)"
>
</swipable-offense-card>
</ion-list>