官术网_书友最值得收藏!

Components in Angular

Angular took this approach by introducing new building blocks called components. Components extend the directive concept we described in the previous section and provide a broader functionality. Here is the definition of a basic Hello world component:

@Component({ 
  selector: 'hello-world', 
  template: '<h1>Hello, {{target}}!</h1>' 
}) 
class HelloWorld { 
  target: string; 
  constructor() { 
    this.target = 'world'; 
  } 
} 

We can use it by inserting the following markup in our view:

<hello-world></hello-world> 
According to the best practices, we should use a selector of type element for components since we may have only a single component per DOM element.

We will take a look at the preceding syntax in more detail later in this book. Now let's briefly describe the functionality that this component provides. Once the Angular application is bootstrapped, it will look at all the elements in the DOM tree and process them. When it finds an element called hello-world, it will invoke the logic associated with its definition, which means that the template of the component will be rendered and the expression between the curly brackets will be evaluated. This will result in the <h1>Hello, world!</h1> markup.

So, to summarize, the Angular core team separated out the directives from AngularJS into two different parts: components and directives. Directives provide an easy way to attach behavior to the DOM elements without defining a view. Components in Angular provide a powerful, and yet simple-to-learn API, which makes it easier to define the user interface of our applications. Angular components allow us to do the same amazing things as AngularJS directives, but with less typing and fewer things to learn. Components extend the Angular directive concept by adding a view to it. We can think of the relation between Angular components and directives the same way as the relation between Composite and Leaf from the diagram we saw in Figure 5.

Conceptually, we can present the relation between directives and Components as inheritance. Chapter 5, Getting Started with Angular Components and Directives, describes these two concepts in further detail.

主站蜘蛛池模板: 雅江县| 科技| 逊克县| 房产| 永定县| 安多县| 石狮市| 藁城市| 丹阳市| 英山县| 宁明县| 许昌市| 莱芜市| 黄大仙区| 瓦房店市| 蒲江县| 江油市| 荥阳市| 阿坝县| 石渠县| 扶绥县| 小金县| 玉环县| 故城县| 措美县| 赫章县| 宁津县| 上林县| 阳城县| 刚察县| 通山县| 肃南| 乐业县| 庐江县| 通渭县| 武平县| 镇巴县| 西乌珠穆沁旗| 深州市| 夏津县| 塘沽区|