Overview
Learning Ng2, handwriting An example of feeling, of course, is classic two-way data binding. Environment
"@angular/core": "^4.0.0" + typescript 2.3.4 Code presentation file organization
Main files in Src/app directory:
├──app.component.html
├──app.component.ts
├──app.module.ts
├──twoway-bind/
│└──twoway-bind.component.ts
The first is the root module app.module.ts, because the Ngmodel directive is used in the twoway-bind.component.ts.
So we must introduce formsmodule here.
I've always reported this wrong. Can ' t bind to ' ngmodel ' since it isn ' t a known ' 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//Remember to write on
],
providers: [],
bootstrap: [Appcomponent]
})
Export class Appmodule {}
And then the root component, app.component.ts, is just a container.
Import {Component} from ' @angular/core ';
@Component ({
selector: ' App-root ',
templateurl: './app.component.html '
})
Export class appcomponent {
}
Implementation of bidirectional binding 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 {
}
}
Note that the above [(Ngmodel)] This writing, () represents the output, [] represents the input, this style can be implemented two-way binding.
The default is one-way data flow in the ANGULAR2, in order to avoid the problem that the data flow in version 1 is too messy, bidirectional binding is implemented indirectly with input and output.
The last is to call this component on the page, in app.component.html:
<app-twoway-bind></app-twoway-bind>
You are welcome to add a correction!