发表于: 2021-08-14 23:57:22
1 2004
今天完成的事情:
今天一直报错,
询问师兄暂时还找不到原因
先去掉括号,先用着,
在Angular里,有两种绑定,一种是数据绑定(Data Binding),另一种是事件绑定(Event Binding)。
数据流从类到视图则是数据绑定,即在类中改变变量的值,UI视图会跟着改变;反之,事件绑定是随着触发UI视图,类中也会产生相应的变化,比如鼠标点击、键盘点击触发事件。双向绑定则是数据绑定+事件绑定的结合。下面讲一一介绍数据绑定、事件绑定和双向绑定。
一、数据绑定 Data Binding
打开使用Angular CLI命令创建一个组件,命名为test
ng g c test
文件根目录如下:
app.component.x 系列为页面的根模块,可由多个components组成,上述的test就是其中之一,每一个component中包括属于自己.html, .css,.ts文件,在根结构中可以引用各个component。
app.component.ts 里可以定义元数据,比如@Component,其里面的templateUrl、styleUrls会告诉 Angular 从哪里获取你为组件指定html和css文件。
方法一:
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; }
方法二:可以使用在元数据里的template和styles直接定义html和css,如下方式
app.component.ts
<h2>
Welcome {{name}}
</h2>
`
, styles: [`
.text-success {
color : green;
}
.text-danger {
color : red;
}
.text-special {
font-style : italic;
}
`]
若使用方法一,则可以在其对应的html中,引用其他模块,比如test模块,以标签<app-test></app-test> 的方式嵌入。
app.component.html
<!--The content below is only a placeholder and can be replaced.--><div style="text-align:center"> <h1> From AppComponent! </h1> <app-test></app-test></div>
1. Property Binding
Property Binding是对html中标签属性进行绑定,下面在test模块下进行一系列绑定操作,在此模块使用上述方法二对进行模块开发,代码皆在test.component.ts下编写。
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h2> Welcome {{name}} </h2> <input id = {{myId}} type = "text" value = "Vishwas"> <input [id] = "myId" type = "text" value = "Wish"> ` , styles: [` .text-success { color : green; } .text-danger { color : red; } .text-special { font-style : italic; } `] }) export class TestComponent implements OnInit { public name = "Dan" public myId = "testId" constructor() { } ngOnInit() { } }
[id] = "myId" 是把在TestComponent里声明的myId的值赋给html的相应标签中id属性,即id = "testId",并绑定该属性。
明天计划:好好研究数据绑定
评论