Angular2:传递对象以将事件从父级绑定到子级 [英] Angular2: Passing an object to bind event from parent to child
本文介绍了Angular2:传递对象以将事件从父级绑定到子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该绑定对标题,字幕,button.icon和button.name都适用,但对button.action无效
The binding works fine for title, subtitle, button.icon and button.name but not for button.action
parent.component.html
parent.component.html
<app-title [title]="title" [subtitle]="subtitle" [buttons]="buttons"></app-title>
parent.component.ts
parent.component.ts
export class ParentComponent {
actionOne() {
...
}
title = 'Title';
subtitle = 'Subtitle';
buttons = [
{ 'name': 'Name1', 'icon': 'Icon1', 'action': 'actionOne()'},
{ 'name': 'Name2', 'icon': 'Icon2', 'action': 'actionTwo()'},
{ 'name': 'Name3', 'icon': 'Icon3', 'action': 'actionThree()'}
];
}
child.component.html
child.component.html
<section>
<div class="text-wrapper">
<h1>{{ title }}</h1>
<h2 *ngIf="subtitle">{{ subtitle }}</h2>
</div>
<template *ngIf="buttons">
<div class="buttons-wrapper">
<button *ngFor="let button of buttons" md-raised-button (click)="button.action"><md-icon *ngIf="button.icon">{{ button.icon }}</md-icon>{{ button.name }}</button>
</div>
</template>
</div>
child.component.ts
child.component.ts
export class ChildComponent {
@Input() title:string;
@Input() subtitle:string;
@Input() buttons:string;
}
推荐答案
可以这样做:
按钮界面:
export interface IButton {
Name: string;
Icon: string;
Action: Function
}
父组件:
@Component({
...
})
export class ParentComponent implements OnInit {
buttons: IButton[] = [
{
Name: 'Hello',
Icon: 'Test',
Action: this.actionOne.bind(this) // we need to make sure this is scoped correctly
}
];
actionOne(){
console.log('This is from action One');
}
constructor() { }
ngOnInit() {
}
}
子组件
@Component({
...
})
export class ChildComponent implements OnInit {
@Input() buttons: IButton[];
constructor() { }
ngOnInit() {
}
}
儿童html
<div *ngIf="buttons">
<button *ngFor="let button of buttons" (click)="button.Action()">{{button.Name}}</button>
</div>
希望有帮助
这篇关于Angular2:传递对象以将事件从父级绑定到子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文