Component 组件
web component标准:
- 自定义元素
- 模板
- Shadow DOM
- Html 导入
Angular组件
- 所有的Angular组件都可以独立存在
- 任何Angular组件都可以作为根组件被引导、路由加载、在其他组件中使用
- 组件不能被单独启动,必须包装到模块(NgModule)中,通过Bootstrap模块接口引导入口模块启动Angular应用
- 组件是Angular最小逻辑单元,模块是组件的抽象
创建Angular组件:
- 从 @angular/core 中引入 Component 装饰器
- 建立一个普通类,并用 @Component 修饰它
-
在 @Component 中,设置 selector 自定义标签和 template 模板
//1 import { Component } from ‘angular/core‘; //2 @Component({ //3 selector: ‘contact-item‘,template:` <div><p>dadada</p></div> ` })
组件的基础构成
-
组件装饰器(Decorator) 每个组件必须使用@Component进行修饰,才能成为angular组件
@Component是TS语法,如果移除@Component,就不是一个组件
-
组件元数据(Metadata) selector、template、templateUrl等
template
组件的内联模板
多行模板使用‘`‘分隔符templateUrls
外部模板
每个组件只能定义一个模板
推荐使用templateUrl,特别是长模板@Component({ template:‘app/components/templateName.html‘ })
styles
组件的内联样式@Component({ styles:[ ` p {color:red;} ` ] })
styleUrls
组件的外联样式
styles 和 styleUrls 可以同时指定,style 优先级更高@Component({ styles:[‘app/list/item.component.css‘] })
-
模板(template) 每个组件都会关联一个模板,此模板最终会渲染到页面上,页面上的DOM元素就是此组件实例的寄宿元素
组件可以与宿主元素交互,组件的交互形式包括:
显示数据
使用插值语法 {{}}} 显示组件数据import { Component } from ‘ @angular/core ‘; @Component({ selector:‘contact-item‘,template:` <div>{{name}}</div> <div>{{phone}}</div> ` }) export class ContactItemComponet{ name :"name"; phone:"12456"; }
双向数据绑定
import { Component } from ‘@angular/core‘; @Component({ selector:‘contact-item‘,template:` <input type="text" value="{{name}}" [(ngModel)]="name"/> <p>{{name}}</p> ` styles:[``] }) export class ContactItemComponent{ //... } //当输入框内容发生改变时,Angular的双向绑定机制会将输入内容同步更新到name属性上,并同步显示到p标签上
监听数组元素事件以及调用组件方法
通过(eventName)方式响应UI事件
一般调用组件方法和事件监听一起使用<h3 (click)="addContact()"></h3>
组件类 组件的逻辑都在组件内部定义并实现
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。