[英]Upgrade AngularJS directive with ngModel to Angular component
我正在嘗試將我的 AngularJS 指令升級到 Angular 組件。
這是指令的代碼:
ng1AppModule.component('ng1Tmp', {
bindings: {p: '<'},
require: {ngModel: 'ngModel'}
});
我嘗試通過以下方式升級它:
@Directive({selector: 'ng1-tmp'})
class Ng1HTmpComponent extends UpgradeComponent{
@Input() p: string;
@Input() ngModel: INgModelController;
constrcutor(elementRef: ElementRef, injector: Injector) {
super('ng1Tmp', elementRef, injector);
}
}
它不能很好地工作。 好像不支持ngModel這種方式升級。 但我在本文檔中沒有看到任何相關信息: https : //angular.io/guide/upgrade 。
有沒有人對此有一些想法?
提前致謝。 :)
Angular 並不是 AngularJS 的新版本,它們是不同的結構。 編寫代碼前必須知道的 3 點組件:Input、Output 和 EventEmitter。
這里的一個示例指令/組件可能會有所幫助。
//AngularJS directive, use it like <pagination></pagination>
app.register.directive('pagination', function () {
return {
restrict : 'E',
scope : true,
templateUrl : '/views/widgets/pagination.html',
controllerAs : 'vm',
controller : PaginationController
};
PaginationController.$inject = ['$scope'];
function PaginationController($scope) {
}
});
現在我在 Angular 上重新定義了它。
//Angular6 Component, use it like
//<app-pagination [pager]="pagination" (fired)="onFire($event)"></app-pagination>
import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-pagination',
templateUrl: './pagination.component.html',
styleUrls: ['./pagination.component.scss']
})
export class PaginationComponent implements OnInit {
@Input() pager: any;
@Output() fired = new EventEmitter<any>();
constructor() { }
ngOnInit() {
}
prev() {
let page = this.pager.current_page - 1;
if (page < 0) page = 1;
this.fired.emit({type: 'page', data: page});
}
next() {
let page = this.pager.current_page + 1;
if (page > this.pager.page_count) page = this.pager.page_count;
this.fired.emit({type: 'page', data: page});
}
}
在父組件或頁面上,應該監聽事件,例如:
onFire(event) {
switch (event.type) {
case 'page': //pagination component fire
return this.gotoPage(event.data);
case 'edit': //list item fire
return this.editArticle(event.data);
case 'view': //list item fire
return this.viewArticle(event.data);
case 'trash': //list item fire
return this.trashArticle(event.data);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.