Angular2之入门示例

前端之家收集整理的这篇文章主要介绍了Angular2之入门示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

在学ng2,手写一个例子感受下,当然是经典的双向数据绑定.

环境

“@angular/core”: “^4.0.0” + Typescript 2.3.4

代码展示

文件组织

src/app 目录下主要文件:
├── app.component.html
├── app.component.ts
├── app.module.ts
├── twoway-bind/
│ └── twoway-bind.component.ts

首先是根模块app.module.ts,由于在twoway-bind.component.ts中使用了NgModel指令,
所以这里一定要引入FormsModule.
我最开始一直报这个错Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’.”.

  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { NgModule } from '@angular/core';
  3. import { FormsModule } from '@angular/forms';
  4.  
  5. import { AppComponent } from './app.component';
  6. import { TwowayBindComponent } from './twoway-bind/twoway-bind.component';
  7.  
  8. @NgModule({
  9. declarations: [
  10. AppComponent,HelloWorldComponent,UserItemComponent,UserListComponent,TwowayBindComponent
  11. ],imports: [
  12. BrowserModule,FormsModule // 记得写上
  13. ],providers: [],bootstrap: [AppComponent]
  14. })
  15. export class AppModule { }

再就是根组件app.component.ts,目前只是一个 容器而已

  1. import { Component } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-root',templateUrl: './app.component.html'
  5. })
  6. export class AppComponent {
  7. }

双向绑定的实现twoway-bind.component.ts:

  1. import { Component,OnInit } from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'app-twoway-bind',template: `
  5. <div>
  6. <input type="text" [(ngModel)]="username">
  7. <p>{{ username }}</p>
  8. </div>
  9. `
  10. })
  11. export class TwowayBindComponent implements OnInit {
  12. username: string = 'Hello World!';
  13.  
  14. ngOnInit(): void {
  15. }
  16. }

注意上面的[(ngModel)]这种写法,()表示输出,[]表示输入,这种写法就可以实现双向绑定了.
angular2中默认是单向数据流,为了避免版本1中的数据流向太乱的问题,使用输入输出间接地实现双向绑定.

最后就是在页面调用这个组件,在app.component.html中:

  1. <app-twoway-bind></app-twoway-bind>

欢迎补充指正!

猜你在找的Angularjs相关文章