Angularv4.初体验


1218 浏览 5 years, 2 months

17 双向数据绑定 Two Way Data Binding

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

17 -- Two Way Data Binding

这一章节开始,我们来介绍搜索模块

首先要引入的是双向数据绑定

创建一个新的component

ng g component search

将selector名字改成search,

@Component({
  selector: 'search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})

在app.component.html里,将search内容换成这个selector

      <search></search>
      <!-- <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form> -->

将form内容移到search.component.html里。

接下来配置data binding,当在某个地方输入内容时,它同时能在其他地方被使用

绑定input到ngModel

<input type="text" class="form-control" placeholder="Search" name="searchQuery" [(ngModel)]='searchQuery'>

报错

Can't bind to 'ngModel' since it isn't a known property of 'input'

查了一下,原因是FormModel没导入 https://stackoverflow.com/questions/38892771/cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-input

在app.models导入

import { FormsModule } from '@angular/forms';
@NgModule({  
  imports: [
    //ngx-bootstraps
    BsDropdownModule.forRoot(),
    CarouselModule.forRoot(),
    BrowserModule,
    AppRoutingModule,
    HttpModule,
    FormsModule,
  ],
})

这个跟HttpModel一样,都是后来添加的,没有在项目创建时生成,后面要查一下为什么。

现在在输入框里输入内容时,相应的按钮上会显示search for ... 加上你输入的内容。

当然,这儿只是给你演示,真正的代码没必要做这个。