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’.".

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { TwowayBindComponent } from './twoway-bind/twoway-bind.component';

@NgModule({
  declarations: [
    AppComponent,
    TwowayBindComponent
  ],
  imports: [
    BrowserModule,
    FormsModule // 记得写上
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
}

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

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-twoway-bind',
    template: `
        <div>
            <input type="text" [(ngModel)]="username">
            <p>{{  username  }}</p>
        </div>
    `
})
export class TwowayBindComponent implements OnInit {
    username: string = 'Hello World!';
    
    ngOnInit(): void {
    }
}

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

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

<app-twoway-bind></app-twoway-bind>

欢迎补充指正!

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值