gpt4 book ai didi

data-binding - 使用 ngModel 的 Angular 2 双向绑定(bind)不起作用

转载 作者:太空狗 更新时间:2023-10-29 16:45:25 28 4
gpt4 key购买 nike

无法绑定(bind)到 'ngModel',因为它不是 'input' 元素的已知属性,并且没有具有相应属性的匹配指令

注意:我使用的是 alpha.31

import { Component, View, bootstrap } from 'angular2/angular2'

@Component({
selector: 'data-bind'
})
@View({
template:`
<input id="name" type="text"
[ng-model]="name"
(ng-model)="name = $event" />
{{ name }}
`
})
class DataBinding {
name: string;

constructor(){
this.name = 'Jose';
}
}

bootstrap(DataBinding);

最佳答案

Angular 已于 9 月 15 日发布了最终版本。与 Angular 1 不同,您可以在 Angular 2 中使用 ngModel 指令进行双向数据绑定(bind),但您需要以有点不同的方式编写它,例如 [(ngModel)] (Banana in a box 语法)。几乎所有 angular2 核心指令现在都不支持 kebab-case,您应该使用 camelCase

Now ngModel directive belongs to FormsModule, that's why you should import the FormsModule from @angular/forms module inside imports metadata option of AppModule(NgModule). Thereafter you can use ngModel directive inside on your page.

app/app.component.ts

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

@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<input type="text" [(ngModel)]="myModel"/>
{{myModel}}
`
})
export class AppComponent {
myModel: any;
}

app/app.module.ts

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

@NgModule({
imports: [ BrowserModule, FormsModule ], //< added FormsModule here
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})

export class AppModule { }

app/main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

Demo Plunkr

关于data-binding - 使用 ngModel 的 Angular 2 双向绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31623879/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com