数据绑定
1.事件绑定
函数调用:
属性赋值:
example:
1.1创建项目
–> ng new demo1
1.2生成组件
–> ng g component bind
1.3
bind.component.html
<p>
bind works!
</p>
<button (click)="doOnClick($event)">点我</button>
bind.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-bind',
templateUrl: './bind.component.html',
styleUrls: ['./bind.component.css']
})
export class BindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
doOnClick(event: any) {
console.log(event);
}
}
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<app-bind></app-bind>
1.4运行
点击按钮,查看控制台
–> npm run start
属性绑定:
bind.component.html
<p>
bind works!
</p>
<!--事件绑定-->
<button (click)="doOnClick($event)">点我</button><br>
<!--属性绑定-->
<img [src]="imgUrl"/>
<!--属性绑定:插值表达式-->
<img src="{{imgUrl}}"/>
bind.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-bind',
templateUrl: './bind.component.html',
styleUrls: ['./bind.component.css']
})
export class BindComponent implements OnInit {
imgUrl: string
imgUrl = 'http://placehold.it/400x220';
constructor() { }
ngOnInit() {
}
doOnClick(event: any) {
console.log(event);
}
}
2.Dom属性绑定
bind.component.html
<p>
bind works!
</p>
<!--事件绑定-->
<button (click)="doOnClick($event)">点我</button><br>
<!--属性绑定-->
<img [src]="imgUrl"/>
<!--Dom属性绑定:插值表达式-->
<img src="{{imgUrl}}"/>
<!--html与Dom绑定的区别-->
<!--浏览器在渲染字符串时,创建相应的Dom节点-->
<input value="Tom" (input)="doOnInput($event)">
==4.双向绑定==
bind.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-bind',
templateUrl: './bind.component.html',
styleUrls: ['./bind.component.css']
})
export class BindComponent implements OnInit {
imgUrl: string
imgUrl = 'http://placehold.it/400x220';
constructor() { }
ngOnInit() {
}
doOnClick(event: any) {
console.log(event);
}
doOnInput(event: any) {
/*打印dom属性,改变*/
console.log('Dom:' + event.target.value);
/*打印html属性,不变*/
console.log('Html:' + event.target.getAttribute('value'));
}
}
注:
<button disabled=’“false”>
禁用:通过html属性修改true,false无效
只能通过dom属性修改true,false
3.html属性
4.双向绑定