前端踩坑Angular(三)

学了赶紧做笔记,证明自己曾经学过

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('')
  });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值