Angular2:传递一个对象将事件从父级绑定到子级

时间:2017-01-20 14:23:52

标签: angular binding components bind communication

绑定适用于title,subtitle,button.icon和button.name但不适用于button.action

parent.component.html

    <app-title [title]="title" [subtitle]="subtitle" [buttons]="buttons"></app-title>

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

<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

export class ChildComponent  {

@Input() title:string;
@Input() subtitle:string;
@Input() buttons:string;

}

2 个答案:

答案 0 :(得分:1)

可以这样做:

按钮界面:

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>

希望有所帮助

答案 1 :(得分:0)

您的代码无法工作,因为您将字符串文字而不是方法引用传递给子代码。例如,在button.action属性中,您的ChildComponent会看到字符串文字"actionOne()",而不是方法actionOne()

为了在声明按钮时传递方法引用,您必须删除方法名称周围的引号和括号,并在其前面添加this.

buttons = [
    { 'name': 'Name1', 'icon': 'Icon1', 'action': this.actionOne },
    { 'name': 'Name2', 'icon': 'Icon2', 'action': this.actionTwo },
    { 'name': 'Name3', 'icon': 'Icon3', 'action': this.actionThree }
]

但是,由于this的{​​{1}}上下文会丢失,因此无效。

我要做的是在按钮声明中使用字符串文字(类似于您的代码,但没有括号,例如ChildComponent'actionOne' ...),并且只要在按钮中单击按钮孩子,我会向父母发出一个'actionTwo'事件:

@Output

请注意,我在发出事件时传递了@Component({ template: ` <button (click)="buttonClicked.emit(button.action)"> {{ button.name }} </button> ` }) export class ChildComponent { @Output() buttonClicked: EventEmitter<string> = new EventEmitter<string>(); } 属性(字符串)。

现在,button.action可以监听该事件并使用收到的字符串作为标识符来决定调用哪个本地方法:

ParentComponent
相关问题