如何在仅重命名组件选择器的Angular Component周围创建包装器? [英] How can I create a wrapper around an Angular Component that only renames the component selector?

查看:68
本文介绍了如何在仅重命名组件选择器的Angular Component周围创建包装器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从React的背景出发,您可以像这样重命名来抽象出应用程序中的库组件:

Coming from a React background, you can abstract out a library component in your app by renaming it like this:

const MyAppTable =(props)=>< LibraryTable ... props/> ;;

我想在Angular中做类似的事情,但是不确定如何获取组件行为的1:1映射.例如,我要这样做:

I want to do something similar in Angular, but am not sure how to get the 1:1 mapping of the component's behaviors. E.g., I want to do this:

< my-app-table [input] ="input"></my-app-table>

<库表[input] ="input"<//库表>(加上在组件中找到的所有其他行为)

推荐答案

函数式编程不是很好吗?

Isn't functional programming great?

您必须采用Angular的面向对象方式.您可以扩展一个组件类,而只需更新要更改的组件元数据.

You have to go the object oriented way with Angular. You can extend a component class and just update the component metadata that you want to change.

@Component({selector: 'my-app-table'})
export class MyAppTableComponent extends LibraryTableComponent { 
     constructor() {
        super()
     }
}

您将必须匹配基类的构造函数参数.否则,Angular不知道依赖项注入是什么.

You will have to match the constructor arguments of the base class. Otherwise Angular doesn't know what the dependency injections are.

这是面向对象编程中的反模式的一部分.如果将基类更新为新版本,除非您更新派生类,否则这可能会破坏功能.

This is a bit of an anti-pattern in object oriented programming. If the base class is updated to a new version this might break the functionality unless you update the derived classes.

因此,首选方法称为封装.这基本上是指<​​em>包装其他组件,但这并不容易.

So the preferred approach is called encapsulation. Which basically means to wrap around the other component, but there is nothing easy about that.

@Component({
    selector: 'my-app-table',
    template: `<library-table [input]="input"></library-table>`
})
export class MyAppTableComponent {
    @Input() input: any;
}

上面的代码需要做更多的工作,但是从代码的角度来看,它们更安全.

The above requires more work but is safer from a code point of view.

抽象与封装之间的区别?

这篇关于如何在仅重命名组件选择器的Angular Component周围创建包装器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆