加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular2之入门示例

发布时间:2020-12-17 09:12:21 所属栏目:安全 来源:网络整理
导读:概述 在学ng2,手写一个例子感受下,当然是经典的双向数据绑定. 环境 “@angular/core”: “^4.0.0” + Typescript 2.3.4 代码展示 文件组织 src/app 目录下主要文件: ├── app.component.html ├── app.component.ts ├── app.module.ts ├── twoway-

概述

在学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,HelloWorldComponent,UserItemComponent,UserListComponent,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>

欢迎补充指正!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读