我是Angular的新手,对Angular JS 1.x一代的经验很少。不过我的问题是关于Angular 2.我正在阅读Components
here和https://angular.io/docs/ts/latest/guide/architecture.html
我正在使用TypeScript,我的问题是:可以说Component是一个类似于Model(非@component注释),类似于Model(在Asp.Net MVC中),因为我们可以将html控件与定义的字段绑定在组件类中OR还是更像控制器?或者还有更多我遗失的东西?
第二个网址中有一个声明,其中说:
我们定义一个Component的应用程序逻辑 - 它支持视图的作用 - 在类
中
上面的陈述增加了我的困惑,因为我们可以在一个与html绑定的类中做很多事情。在文本更改时,我们可以远程检查某些内容或按钮单击,我们可以调用方法,所有这些都可以在组件类中定义。那么组件的限制到底是什么?我们可以像模特或类似控制器一样对待它们吗?
请帮我澄清一下
答案 0 :(得分:3)
实际上,组件类对应于组件实现。我的意思是你自己的处理:
因此组件类可以看作是Angular1控制器和范围的混合。
@Component
装饰器将使组件成为Angular2的一部分。我的意思是参与框架和应用程序的不同功能和机制。
可以使用不同的东西配置组件来引用一些:
@Input
和@Ouput
此外,您可以看到类装饰器(@Component
装饰器属于此类型)作为一种拦截器:
因此,@Component
装饰器对于配置组件并使其成为Angular2机制的一部分非常重要。
请注意每个人:我试图简单地描述这一点,这与我对事物的理解相对应,但我可以随意评论我的答案; - )
答案 1 :(得分:1)
Directives/components replace the mix of controllers, scopes, and directives from AngularJS (Angular 1).
A component is a view and an associated view controller. (Directives don't have views.) Components are how we create views for our application and support those views with (minimal) state, data, and logic.
A view is an HTML template with some additional Angular syntax that controls an area of the screen/display. The component exposes some (subset!) of the application data to a view, and it handles the UI logic for the view. Data should not be owned by components. Rather the component should get references to only the data it needs to drive the view. (This is similar to the same best practice used in AngularJS -- controllers should get references to data, not own it.) Services should normally own data.
Similarly, component logic should be limited to the logic needed to drive the view (hence, "view logic"). Application logic belongs in services. Other tasks also belong in services and not in components: validating user input, logging, interacting with (web) servers, etc.
So, components (like AngularJS controllers) should be as "thin" as possible. They should handle user interaction and define the data bindings required for such. They should be focused on supporting the view.
Angular creates and destroys components as necessary as the user interacts with the application. Components have a lifecycle, and there are lifecycle hooks that we can tap into.
A component is just a class until we tell Angular about it. And we do that by attaching metadata to the class.
I find it more important to know what belongs in a component and what doesn't, rather than trying to determine if it is a "controller" or a "model" -- those terms are so broad and overused that I don't think you can get two developers to agree on a definition of either term.
Some of the above sentences are likely copied from the Angular.io docs, blogs, other SO posts, etc. I have a bunch of notes about Angular in a document, and I don't always keep track of source references.