【问题标题】:How to catch an event from a custom component(button) that is rendered into an ng2-smart-table如何从呈现为 ng2-smart-table 的自定义组件(按钮)中捕获事件
【发布时间】:2017-07-16 19:53:41
【问题描述】:

我试图在 Angular2 中发出一个事件,方法是单击子组件中的一个按钮,该按钮在父组件中作为列呈现的 ng2-smart-table 内呈现。由于没有选项可以在我呈现的子组件的标签中添加事件侦听器(我需要在标签内进行).. 这样,它只被渲染而没有提供任何属性的选项。 提前致谢!

【问题讨论】:

  • 嗨,欢迎来到堆栈溢出。请参阅How to Ask 链接以获取有关如何提出问题并相应更新您的问题的更多详细信息。

标签: angular typescript


【解决方案1】:

从自定义组件中获取值

你必须在 smartable 的设置中声明,到父组件中

   setting.columns.button: {
            title: 'Actions',
            filter: false,
            type: 'custom',
            renderComponent: ActionButtonComponent,
            onComponentInitFunction(instance) {
              instance.save.subscribe(row => {
                console.log(this)
              });
            }
          }

和子组件

@Component({
  selector: 'app-action-button',
  template: `
 <span ngbDropdown>
    <button class="btn btn-danger btn-raised mr-1" id="dropdownRaised4" ngbDropdownToggle>Actions</button>
    <div ngbDropdownMenu class="dropdown-menu-right" aria-labelledby="dropdownRaised4">
      <button class="dropdown-item ontop" (click)="onClick(event)">
        <i class="icon-x"></i>Cancel</button>
    </div>
  </span>`,
  styleUrls: ['./action-button.component.scss']
})
export class ActionButtonComponent implements ViewCell, OnInit {
  renderValue: string;
  @Input() value: string | number;
  @Input() rowData: any;

  @Output() save: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
    this.renderValue = this.value.toString().toUpperCase();
  }

  onClick(row) {
    this.save.emit(row);
  }


}

【讨论】:

  • 虽然此代码 sn-p 可以解决问题,但 including an explanation 有助于提高您的回复质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 嘿,你能告诉我如何用父组件的数据初始化组件吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多