Angularv4.初体验


921 浏览 3 years, 10 months

18 表单基础 ngForm Basics

版权声明: 转载请注明出处 http://www.codingsoho.com/

18 -- ngForm Basics

给form添加method和action如下,但它并不工作

  <form class="navbar-form navbar-left" method="get" action="/search/">

修改代码如下

  • 用ngSubmit来做表单提交处理
  • 用ngModel来实现双向数据绑定
  • (change)处理onchange事件
  <form #searchForm="ngForm" class="navbar-form navbar-left" (ngSubmit)='submitSearch($event,searchForm) '>
    <input type="hidden" name="location" [(ngModel)]='searchLocation'>
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search" name="q" [(ngModel)]='searchQuery' (change)='searchQueryChange()'>
    </div>
    <button type="submit" class="btn btn-default">
        Search
    </button>
  </form>

在search.component.ts里的处理函数如下

  • searchLocation进行了初始化,它跟input[name="location"]是绑定的,也可以在input里面设置value="New Beach"
  • 只有通过ngModel进行数据绑定,console.log(formData.value)才能打印出值来,否则为空
  searchLocation = "New Beach"
  submitSearch(event, formData){
      console.log(event)
      console.log(formData.value)
  }

  searchQueryChange(){
      this.searchLocation = "Shanghai"
  }

如果要提交,我们可以用this.http.post(endpoint, data={})

详情查看 https://angular.io/api/forms/NgForm