Angular:覆盖组件的功能

时间:2016-07-27 21:32:18

标签: angular angular2-template angular2-services

我是Angular的新手,我的部分问题是我不知道究竟是什么,所以我不知道在哪里研究。

我正在构建一个保存按钮组件。这在整个应用程序中存在10次以上,并且在每个视图中具有相同的外观和位置。但是,保存功能会有所不同,可能需要根据您点击的位置进行一些独特的表单验证。

此时保存按钮组件非常精简,并使用Angular Material。

import * as save from './buttonSave';

import './buttonSave.component.less';

@save.Component({
    selector: 'ui-buttonSave',
    template:
`
<button md-fab color="accent">
   <md-icon class="md-24">save</md-icon>
</button>
`,
    directives: [save.MdButton, save.MdIcon],
    viewProviders: [save.MdIconRegistry]
})

export class ButtonSaveComponent {

}

我想要做的是包括一个默认的点击行为,它会路由到位于模板中使用此保存组件的父组件中的某个本地保存功能。要使用此保存按钮组件,我需要做的(理论上)是将其粘贴在模板中,导入/列出指令(可能列出提供程序?),然后覆盖该组件的保存功能(也许它可以被称为saveClick或其他东西)。

我真的不知道这会在Angular中使用什么来实现这一目标... EventEmitter?输出?提供商?

我知道只要我使用这个保存组件,我就可以回避这个...

<ui-buttonSave (click)="localSave($event)"></ui-buttonSave>

但我宁愿使用Angular给我的所有铃声和口哨声。非常感谢任何方向/帮助!

2 个答案:

答案 0 :(得分:1)

看起来您正在创建可重用的UI组件,因此保存操作/行为不应该(不能)成为该组件的一部分。尝试覆盖(抽象)“保存”组件函数更多的是面向对象的设计方法,而不是Angular组件方法(在发生某些用户操作时发出事件)。

所以,我建议你通过绑定到现有的DOM click事件,将保存动作/行为委托给父,就像你提到的那样:

<ui-buttonSave (click)="save($event)"></ui-buttonSave>

或定义并绑定到自定义事件(需要EventEmitter):

<ui-buttonSave (saveRequested)="save($event)"></ui-buttonSave>

关于验证用户输入,请参阅文档:https://angular.io/docs/ts/latest/guide/architecture.html#!#services

  

我们更喜欢我们的组件类精益。我们的组件不从服务器获取数据,它们不验证用户输入,也不直接登录到控制台。他们将这些任务委托给服务。

答案 1 :(得分:0)

您可以使用指令覆盖第三方组件的功能

<button md-fab color="accent" someDirective>
   <md-icon class="md-24">save</md-icon>
</button>

创建按钮中使用的指令

import { Directive } from '@angular/core';
import { Host, Self, Optional } from '@angular/core';

@Directive({
    selector: '[someDirective]',
})
export class SomeDirectiveDirective {
    
    constructor(
      @Host() @Self() @Optional() public hostSel : Select) {
      // Now you can access specific instance members of host directive
      let app = (<any>hostSel)._app;
      // also you can override specific methods from original host directive so that this specific instance uses your method rather than their original methods.
      hostSel.click= (ev?: UIEvent) => {
        // your custom code for save() method here..
      }
    }
}

https://medium.com/angular-in-depth/changing-the-behavior-of-a-3rd-party-angular-component-91f84fb9af28

相关问题