UpgradeComponent
Experimental Class
Что он делает
Часть библиотеки upgrade/static для приложений гибридного обновления, поддерживающих компиляцию AoT
Позволяет использовать компонент Angular 1 в шаблонах Angular 2+.
Как использовать
Предположим, у вас есть компонент Angular 1 с именем ng1Hero , который необходимо сделать доступным в шаблонах Angular 2+.
// This Angular 1 component will be "upgraded" to be used in Angular 2+
ng1AppModule.component('ng1Hero', {
bindings: {hero: '<', onRemove: '&'},
transclude: true,
template: `<div class="title" ng-transclude></div>
<h2>{{ $ctrl.hero.name }}</h2>
<p>{{ $ctrl.hero.description }}</p>
<button ng-click="$ctrl.onRemove()">Remove</button>`
});
Мы должны создать Directive, который сделает этот компонент Angular 1 доступным в шаблонах Angular 2+.
// This Angular 2 directive will act as an interface to the "upgraded" Angular 1 component
@Directive({selector: 'ng1-hero'})
class Ng1HeroComponentWrapper extends UpgradeComponent implements OnInit, OnChanges, DoCheck,
OnDestroy {
// The names of the input and output properties here must match the names of the
// `<` and `&` bindings in the Angular 1 component that is being wrapped
@Input() hero: Hero;
@Output() onRemove: EventEmitter<void>;
constructor(@Inject(ElementRef) elementRef: ElementRef, @Inject(Injector) injector: Injector) {
// We must pass the name of the directive as used by Angular 1 to the super
super('ng1Hero', elementRef, injector);
}
// For this class to work when compiled with AoT, we must implement these lifecycle hooks
// because the AoT compiler will not realise that the super class implements them
ngOnInit() { super.ngOnInit(); }
ngOnChanges(changes: SimpleChanges) { super.ngOnChanges(changes); }
ngDoCheck() { super.ngDoCheck(); }
ngOnDestroy() { super.ngOnDestroy(); }
}
В этом примере вы видите, что мы должны унаследовать от базового класса UpgradeComponent, но также предоставить декоратор @Directive. Это необходимо, так как компилятор AoT требует, чтобы эта информация была доступна статически во время компиляции.
Обратите внимание, что необходимо:
- указать селектор директивы (
ng1-hero) - указать все входные и выходные данные, ожидаемые компонентом Angular 1
- унаследовать от
UpgradeComponent - вызвать базовый класс в конструкторе, передав
- имя компонента Angular 1 (
ng1Hero) ElementRefиInjectorдля обёртки компонента
- имя компонента Angular 1 (
Обзор класса
class UpgradeComponent implements OnInit, OnChanges, DoCheck, OnDestroy {
constructor(name: string, elementRef: ElementRef, injector: Injector)
ngOnInit()
ngOnChanges(changes: SimpleChanges)
ngDoCheck()
ngOnDestroy()
}
Описание класса
Вспомогательный класс, который следует использовать в качестве базового класса для создания директив Angular, которые оборачивают компоненты Angular 1, которые необходимо «обновить».
Конструктор
constructor(name: string, elementRef: ElementRef, injector: Injector)
Создаёт новый экземпляр UpgradeComponent. Обычно вам не нужно делать это самостоятельно. Вместо этого вы должны создать новый класс, унаследованный от этого, и вызвать конструктор предка в базовом классе.
// This Angular 2 directive will act as an interface to the "upgraded" Angular 1 component
@Directive({selector: 'ng1-hero'})
class Ng1HeroComponentWrapper extends UpgradeComponent implements OnInit, OnChanges, DoCheck,
OnDestroy {
// The names of the input and output properties here must match the names of the
// `<` and `&` bindings in the Angular 1 component that is being wrapped
@Input() hero: Hero;
@Output() onRemove: EventEmitter<void>;
constructor(@Inject(ElementRef) elementRef: ElementRef, @Inject(Injector) injector: Injector) {
// We must pass the name of the directive as used by Angular 1 to the super
super('ng1Hero', elementRef, injector);
}
// For this class to work when compiled with AoT, we must implement these lifecycle hooks
// because the AoT compiler will not realise that the super class implements them
ngOnInit() { super.ngOnInit(); }
ngOnChanges(changes: SimpleChanges) { super.ngOnChanges(changes); }
ngDoCheck() { super.ngDoCheck(); }
ngOnDestroy() { super.ngOnDestroy(); }
}
- Параметр
nameдолжен содержать имя директивы Angular 1. - Параметры
elementRefиinjectorдолжны быть получены из Angular с помощью инъекции зависимостей в конструктор базового класса.
Обратите внимание, что мы должны вручную реализовать жизненные циклы, которые вызывают базовый класс. Это происходит потому, что в данный момент компилятор AoT не может определить, что UpgradeComponent уже реализует их, и поэтому не подключает вызовы к ним во время выполнения.
Подробное описание класса
ngOnInit()
ngOnChanges(changes: SimpleChanges)
ngDoCheck()
ngOnDestroy()
экспортировано из @angular/upgrade/static, определено в @angular/upgrade/src/aot/upgrade_component.ts
© 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v2.angular.io/docs/ts/latest/api/upgrade/static/UpgradeComponent-class.html