我刚刚写了一篇关于这个的文章。看看它是否有帮助:https://medium.com/@scottmgerstl/slide-a-view-in-from-off-screen-nativescript-angular-8e305f50217a
这是随附的代码:
snackbar.directive.ts
import { Directive, ElementRef, EventEmitter, Output } from '@angular/core';
import { screen, ScreenMetrics } from 'platform';
const screenScale: number = screen.mainScreen.scale;
const offScreenMargin: number = screen.mainScreen.heightDIPs * -1;
@Directive({
selector: '[snackbar]'
})
export class SnackbarDirective {
// Let an implementor know when the view has left the screen
@Output() private dismissed: EventEmitter<boolean> = new EventEmitter<boolean>(false);
private element: ElementRef;
constructor(el: ElementRef) {
this.element = el;
this.element.nativeElement.marginBottom = offScreenMargin;
}
public show(): void {
this.element.nativeElement.animate({
translate: { x: 0, y: this.getTranslateYHeight() * -1 },
duration: 750
});
}
public dismiss(): void {
this.element.nativeElement.animate({
translate: { x: 0, y: this.getTranslateYHeight() },
duration: 750
})
.then(() => this.dismissed.emit(true));
}
private getTranslateYHeight(): number {
return this.element.nativeElement.getMeasuredHeight() / screenScale;
}
}
implementor.component.html
<GridLayout columns="auto,auto" rows="auto,auto">
<!-- My Component Page Markup -->
<Button (tap)="onOpenButtonTap($event)"
text="Open" row="0" col="0"></Button>
<Button (tap)="onCloseButtonTap($event)"
text="Close" row="0" col="1"></Button>
<StackLayout snackbar class="slide" col="0" colSpan="2" row="1">
</StackLayout>
</GridLayout>
implementor.component.ts
import { Component, ViewChild } from '@angular/core';
import { SnackbarDirective } from './snackbar.directive';
@Component(...)
export class ImplementorComponent {
@ViewChild(SnackbarDirective) private snack: SnackbarDirective;
private onOpenButtonTap(): void {
this.snack.show();
}
private onCloseButtonTap(): void {
this.snack.dismiss();
}
}
这是怎么回事:
使用指令选择器[snackbar] 中的括号表示法,您可以将指令(包括组件)附加到元素,而不是将它们嵌套在其他视图中(在上面提到的博客文章中进行了解释)。为了访问指令的方法,您可以使用来自 angular core@ViewChild(SnackbarComponent) 的 ViewChild 装饰器按类型在实现组件中引用它。请注意,如果您想向同一类型的视图添加多个指令,则需要使用 @ViewChildren() 装饰器并遍历以找到您想要的。