Angular 2 Bind HTML Inputs To Component Variables Like In Vue?
So I've been struggling with this for a long time...I've been looking into the docs, but there are so many different directives and ways to communicate between components and the D
Solution 1:
I think what you're looking for is [(ngModel)]
which is used for two-way data binding.
<input
id="customerName"
class="form-control"
required
[(ngModel)]="customer_form.name"
name="name">
PS: To use the [(ngModel)]
, you'll have to import FormsModule
and then add it the the imports
array of your AppModule
or whatever module you're using it in.
...
import { FormsModule } from '@angular/forms';
...
@NgModule({
imports: [
...,
FormsModule,
...
],
...
})
export class AppModule { }
Solution 2:
I have created a simple example of binding in a template-driven form: https://stackblitz.com/edit/angular-m2tkrf
Note that FormsModule is imported in app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; //<---- IMPORTED
import { AppComponent } from './app.component';
import { HeroFormComponent } from './hero-form/hero-form.component';
@NgModule({
imports: [
BrowserModule,
FormsModule //<---- IMPORTED IN MODULE
],
declarations: [
AppComponent,
HeroFormComponent
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Solution 3:
Use ngModel for two-way data binding
put [(ngModel)] on the input to pass the data from & to your property like this:
//app.module code
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; //<---- IMPORTED
import { AppComponent } from './app.component';
import { TablesComponent } from './tables.component'; //<---- IMPORTED
@NgModule({
imports: [
BrowserModule,
FormsModule //<---- IMPORTED IN MODULE
],
declarations: [
AppComponent,
TablesComponent //<---- IMPORTED
],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule { }
//--------------------------tables.component.html
<input id="customerName" class="form-control" [(ngModel)]="customer_form.name" required>
Post a Comment for "Angular 2 Bind HTML Inputs To Component Variables Like In Vue?"