angular - 带有视图模型前缀 (vm) 的 Angular 8 UI 模型绑定
问题描述
我们的团队目前正在将 AngularJS 应用程序重写为 Angular 8+。我们现有的结构vm.model
在 AngularJS 中用作我们的视图模型。以下参考文章(和其他来源)似乎不再使用vm.*
前缀。
https://angular.io/guide/ajs-quick-reference
我们处于开发初期;并开始使用集中式模型vm.*
前缀进行 UI 模型绑定。前缀很熟悉,有助于将模型共享集中到 UI。(下面的例子)。
vm: any;
let model = new CartItem();
let product = initData['product'] as Product;
this.vm = {
model: model,
selectedProduct: product
};
我们的团队中没有注册的 Angular 8 专家,但我们都是 Angular 1.x-perts。因此,我们对这种方法没有指导。
vm.*
对我们的对象绑定使用前缀是否有长期的负面影响?你有什么理由可以指出为什么这种方法是个坏主意?
解决方案
你一定见过,组件有3个文件:
- html
- css/sass/scss
- ts
所以,例如在foo.component.ts
(我使用.sass)
@Component({
selector: 'app-foo',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.sass']
})
export class FooComponent {
itIsAAttirbute: number = 0; // html only read
inputAttr: string = ''; // read-write
anotherText: string = 'string'; // pass into "another-componenet"
construct() {
setInterval(() => { this.itIsAAttirbute++; }, 1000);
}
clickEventMethod() {
// code
}
}
foo.component.html
<p>{{ itIsAAttirbute }}</p>
<input [(ngModel)]="inputAttr"/>
<another-component [componentInputProperty]="anotherText" (click)="clickEventMethod()">
<another-component>
来源:https ://angular.io/guide/template-syntax#binding-syntax-an-overview
因此,您可以看到它和所有属性。不需要模型。Ofc,如果您想使用<form>
我不推荐[(ngModel)]
. 使用它们:
或者你定义一个类,用“接口”和“类”描述一个模型。
我推荐:https ://www.udemy.com/course/the-complete-guide-to-angular-2/
更新:我在nesterenes 的#1 评论之后写了它。
您的想法仅取决于实施。可能的。vm
只是一个对象。
@Component({
selector: 'app-foo',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.sass']
})
export class FooComponent {
vm = {
itIsAAttirbute: number = 0; // html only read
inputAttr: string = ''; // read-write
anotherText: string = 'string'; // pass into "another-componenet"
};
construct() {
setInterval(() => { this.vm.itIsAAttirbute++; }, 1000);
}
clickEventMethod() {
// code
}
}
<p>{{ vm.itIsAAttirbute }}</p>
<input [(ngModel)]="vm.inputAttr"/>
<another-component [componentInputProperty]="vm.anotherText" (click)="clickEventMethod()">
<another-component>
推荐阅读
- python - 如何在 Python 中为 Excel 创建新行?
- sql - TINYMCE 长度:asp.net mvc
- reporting-services - 如何在SSRS中计算组中的百分比
- javascript - 如何使用反应导航更新 stacknavigator 上的自定义标题?
- php - 添加模糊性时,Elasticsearch 返回一个奇怪的结果
- linux - shell if 语句执行,即使它不是真的
- node.js - 在柏树中找到或未找到 P 元素
- haskell - 类型的约束多态性
- python - Tkinter colorchooser 甚至无需导入即可运行
- wso2 - 试试这个用于招摇的 API 在 wso2 EI 6.4 中不起作用