学了赶紧做笔记,证明自己曾经学过
Angular绑定事件
在标签内部使用小括号输入需要绑定的事件类型,等号后面写上绑定的方法,仅此而已
<button (click)="clickMe()">点击</button>
export class HellowordComponent implements OnInit {
constructor() { }
clickMe():void{
alert(123)
}
}
document.getElementById().value可以获取输入框的值,而在Angular简化不少,只需要在输入框绑定一个id,后面就可以直接使用了,好像这样
<input #userName placeholder="用户名" type="text">
<button (click)="clickMe(userName.value)">点击</button>
export class HellowordComponent implements OnInit {
clickMe(userName:string):void{
alert(userName)
}
}
Angular双向绑定
在Angular中使用数据双向绑定,要先引入app.module.ts中引入FormsModule
import { FormsModule } from '@angular/forms';
然后再导入模块当中
@NgModule({
declarations: [
AppComponent,
HellowordComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
最后在输入框中添加属性,中小括号内容是固定的,等号后面的是需要双向绑定的变量
<input [(ngModel)]="sthName">
<h3>{{sthName}}</h3>
对象属性双向绑定
上面使用FormControl 进行绑定的是单属性绑定,日常使用最多的还是修改对象的某个字段,单属性绑定明显就不够用,非要用也可以,就把对象的属性拆分,如果这样就太麻烦了,所以选择formGroup配套FormControl
使用formGroup的时候先要在当前模块导入,
import { FormControl, FormGroup } from '@angular/forms';
在表单中绑定一个[formGroup]=“student”,中括号内容固定,等号后面是需要绑定的对象,表单内绑定对象各个属性formControlName=“sId”
<form action="" [formGroup]="student">
<input type="text" formControlName="sId">
<input type="text" formControlName="sName">
<button (click)="showMe()">show</button>
</form>
student对象结构
student:FormGroup=new FormGroup({
sId:new FormControl(''),
sName:new FormControl('')
});