我想将组件中的Company对象绑定到我的视图中。这在AngularJS中很容易,但是当我在Angular 2中执行此操作时出现错误。
查看
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
mAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
int appbarHeight=appBarLayout.getHeight(); // or measured height
int totalHeightOfDevice=height;
int absoluteHeight=height-appbarHeight;
// position your view to absolute height..
}
});
组件:
<input type="text" class="form-control" [(ngModel)]="company.name"
placeholder="Company Name" required>
<input type="text" class="form-control" [(ngModel)]="company.address1"
placeholder="Address Line 1" id="address1" required>
<button class="btn btn-primary pull-right next-btn" (click)="show()">Next</button>
错误:
company: Company;
constructor(
private router: Router
) { }
ngOnInit() { }
show() {
console.log(this.company);
}
答案 0 :(得分:1)
您正在尝试使用模板驱动表单,如果您对Reactive Form感兴趣,请参阅以下网站
https://toddmotto.com/angular-2-forms-reactive
您可以将以下代码用于(模板驱动表单)参考。
<code>
import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app',
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
<div>Username: <input type="text" name="username" ngModel></div>
<div>SSN: <input type="text" name="ssn" ngModel></div>
<div>Password: <input type="password" name="password" ngModel></div>
<div>Confirm password: <input type="password" name="pconfirm" ngModel></div>
<button type="submit">Submit</button>
</form>
`
})
class AppComponent {
onSubmit(formData) {
console.log(formData);
}
}
@NgModule({
imports : [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap : [ AppComponent ]
})
class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
</code>
答案 1 :(得分:0)
如果您在表单中使用ngModel
,则必须将选项设置为[ngModelOptions]="{standalone: true}"
,如果您有,则必须为每个控件设置name
属性。
答案 2 :(得分:0)
@Rahul说我必须从@ angular / forms模块导入NgForm才能工作
答案 3 :(得分:0)
只需初始化您的对象一次。
company: Company = new Company(); // Changes
constructor(
private router: Router
) { }
ngOnInit() { }
show() {
console.log(this.company);
}
答案 4 :(得分:0)