我开始从Angular 1过渡到Angular 2.我尝试先做一些简单的事情,所以我写了一个组件:
import {Component} from 'angular2/core';
import {NgModel} from 'angular2/common';
@Component({
selector: 'app',
template: `
<div>
<div>Value is {{ value }}</div>
<input type="text" [(ngModel)]="value" />
</div>
`,
directives: [NgModel]
})
export class App {
value: string;
};
<!DOCTYPE html>
<html>
<head>
<title>Angular2</title>
</head>
<body>
<app></app>
<script src="./js/bundle.js"></script>
</body>
</html>
(bundle.js只进行app
组件的引导)
我希望在文本框中输入内容后,我应该在div
中获得相同的文字。但它并没有发生。
为什么我的代码不起作用?
此致 Sarun
更新我认为我可能错误地配置了我的构建系统,因此我添加了gulpfile.js
,package.json
和boot.ts
。
gulpfile.js
var gulp = require('gulp');
var browserify = require('browserify');
var tsify = require('tsify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('ts', function() {
browserify({
debug: true
})
.add('source/ts/boot.ts')
.plugin(tsify)
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/js'));
});
gulp.task('watch', function() {
gulp.watch('source/ts/**/*.ts', ['ts']);
});
的package.json
{
"name": "hello-angular2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"angular2": "^2.0.0-beta.0",
"es6-promise": "^3.0.2",
"es6-shim": "^0.34.0",
"reflect-metadata": "^0.1.2",
"rxjs": "^5.0.0-beta.0",
"zone.js": "^0.5.10"
},
"devDependencies": {
"browserify": "^12.0.1",
"gulp": "^3.9.0",
"gulp-exec": "^2.1.2",
"gulp-live-server": "0.0.29",
"gulp-sourcemaps": "^1.6.0",
"gulp-uglify": "^1.5.1",
"gulp-watch": "^4.3.5",
"lite-server": "^1.3.2",
"tsify": "^0.13.1",
"typescript": "^1.7.5",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
}
}
boot.ts
import 'reflect-metadata';
import {bootstrap} from 'angular2/platform/browser';
import {App} from './app';
bootstrap(App);
答案 0 :(得分:3)
问题是您导入的_id
是否有效(或需要)将其取出并且运行正常,请参阅此处:
答案 1 :(得分:2)
经过长时间深入研究文档和漫长的谷歌搜索,我终于找到了答案。
(此答案将来可能有所变化,请参阅Angular文档)
https://github.com/angular/angular/blob/master/modules/angular2/docs/bundles/overview.md
正如@pixelbits所提到的,我错过了几个依赖项rxjs
和angular2-polyfills
,后者是两个其他依赖项zone.js
和reflect-metadata
的填充,这必须是仅包含在<script>
标记中。
我需要做的是:
reflect-metadata
移除boot.ts
导入,并为其添加rxjs
导入。<script>
angular2-polyfills.js
的{{1}}代码
醇>
瞧!它按预期工作。
感谢@pixelbits,@ Zyzle和@GünterZöchbauer帮助我。
答案 2 :(得分:0)
您需要添加FORM_DIRECTIVES
,NgModel
是不够的。
当我只添加No value accessor for '' in [AST]
(在Dart中)时,我收到错误NgModel
。
example in the code documentation也使用FORM_DIRECTIVES