angular6双向绑定

文章参考

angular 常用模块

如果不引入该模块,会出现编译器不报错,但是浏览器不显示内容的奇怪现象

引入 FormsModule

import { FormsModule }   from '@angular/forms';

案例

/**
 * 告诉angular 如何组装应用
 */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { HttpClientModule }   from '@angular/common/http';

import { AppComponent } from './app.component';
import { HeaderComponent } from './page/header/header.component';
import { NewsComponent } from './page/news/news.component';
import {StorageService} from './page/service/storage.service'
import { AppRoutingModule }     from './router/app-routing.module';
import { HttpdemoComponent } from './page/httpdemo/httpdemo.component';

//@NgModule 装饰器将AppModule标记为Angular 模块类(也叫做 NgModule类)
// @NgModule 接收一个元数据对象,告诉Angular 如何编译和启动应用
@NgModule({
  // 引入当前项目运行的组件,自定义组件都需要引入并且在这里声明
  // 依赖注入
  declarations: [
    AppComponent,
    HeaderComponent,
    NewsComponent,
    HttpdemoComponent
  ],
  // 当前项目依赖哪些模块
  imports: [
    BrowserModule,
    HttpClientModule,
    // 如果要引入双向绑定,则需要引入FormModule
    FormsModule,
    AppRoutingModule
  ],
  // 定义服务
  providers: [
    StorageService
  ],
  // 默认启动哪个组件
  bootstrap: [AppComponent]
})

// 根模块不需要导出任何东西,因为其他组件不需要导入根模块,但是一定要写
export class AppModule { }
<input type="text" [(ngModel)]="username">
import { Component, OnInit } from '@angular/core';
import {StorageService} from '../service/storage.service';

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
  public  username: any;

  // 构造方法中添加service类型,就是依赖注入
  constructor(storageService: StorageService) {
    this.username = "username";
  }
  ngOnInit() {
  }

}

猜你喜欢

转载自blog.csdn.net/hbiao68/article/details/84563439