angular - @Input 和 Angular2 Components 中的输入有什么区别?

标签 angular

我正在思考这个问题,找不到任何解释。

在 Angular2 中向组件传递参数时

给定

<my-component [attr]="someModelVariable"></my-component>

似乎有两种接受attr绑定(bind)值的方法:

@Component{(
    selector: "my-component",
    inputs: ["attr"]
)}
export class MyComponent {
}

或者你这样做:

@Component{(
    selector: "my-component"
)}
export class MyComponent {
    @Input()
    public attr: any;
}

而且我确实看到过同时使用两者的代码,谁能解释一下它们之间的区别是什么?

/瑞卡德

最佳答案

虽然 Eric 已经在评论中提供了答案,但我还是要加上我的 2 美分。

使用inputs 的一个优点是类的用户只需要查看传递给@Component 装饰器的配置对象就可以找到输入(和输出)属性。

使用@Input 的一个优点是我们可以定义类型以及它是私有(private)的还是公共(public)的:

@Input() public attr: string;

请注意样式指南 recommends使用 @Input:

Do use @Input and @Output instead of the inputs and outputs properties of the @Directive and @Component decorators.

关于angular - @Input 和 Angular2 Components 中的输入有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648586/

相关文章:

javascript - 将树数据转换为具有层次结构路径的平面数据作为数组

javascript - karma : Move Folder -> Missing Error Handler on Socket?

javascript - 'string' 类型的参数不可分配给 'AbstractControl' 类型的参数。 Angular react 形式

http - Angular 2私有(private)变量消失

javascript - HTML 字符串无法正确显示

javascript - 如何在js中创建 TreeView

angular2-cli 包括自定义字体

c# - 带有 Angular 6 的 .Net Framework 4.5 中的 CORS 问题

angular - 如何在 Angular 2 中识别 Typescript 中的 HTML 元素

javascript - 根据 TypeScript 中的条件将数据从一个数组推送到另一个数组