【发布时间】:2016-06-08 22:15:30
【问题描述】:
我正在使用 Angular 2 构建一个 nativescript 移动应用程序。我有一个“页面”组件,其中包括一个“部分”组件,其中包含一个“按钮”组件。我曾经只有一个组件,但现在将其全部分解,按钮有一个触发动画的点击处理程序,调用的函数如下:
export function socialAnimate(page, clicked) {
var google = page.getViewById("google");
}
按钮组件在哪里调用它:
@Component({
selector: "button",
template: `<Button row="8" col="2" icon="res://key" class="login" rippleColor="#f1f1f1" (tap)="socialClick()"></Button>`,
styleUrls: ["Components/Button/login.css"],
directives: []
})
export class Button implements OnInit {
page: Page;
loginClicked: boolean = false;
ngOnInit() {
this.page = <Page>topmost().currentPage;
}
socialClick() {
this.loginClicked = socialAnimate(this.page, this.loginClicked);
}
}
但是,在重构代码以生成这些子组件后,我收到了一个错误:
TypeError: 无法读取未定义的属性“样式”
我已经使用了调试器,页面已定义,但 getiewById 都没有工作,我想我得到了错误页面?但是为什么 topmost() 不工作,或者其他可能有问题?
更新:
我也试过这种方法:
export class PageCmp {
page: Page;
ngOnInit() {
this.page = <Page>topmost().currentPage;
this.page.actionBarHidden = true;
}
@ViewChild(Button) child: Button;
ngAfterViewInit() {
this.child.setPage(this.page);
}
}
然后在我的按钮组件中添加了函数:
setPage(page: Page) {
this.page = page;
}
编辑:
所以我现在有了这个按钮组件:
import {Component, ViewChild, ElementRef} from "@angular/core";
@Component({
selector: "button",
template: `<FAB row="8" col="2" icon="res://google" class="fab-button" id="google" rippleColor="#f1f1f1" (tap)="login('Google')"></FAB>`,
directives: []
})
export class Button {
@ViewChild('google') google: ElementRef;
socialClick() {
if (this.loginClicked == false) {
this.google.nativeElement.style.opacity = 1;
}
this.loginClicked = !this.loginClicked;
}
}
但是,@ViewChild('google') google: ElementRef; 因此我收到一个错误:
TypeError: 无法读取未定义的属性“nativeElement”
【问题讨论】:
-
更新后的方法会发生什么?
this.child在ngAfterViewInit()中有一些价值。你能在那里console.log(this.child)或者通过其他方式调试吗? -
如果你想以这种方式查询
<FAB元素,它需要有一个像<FAB #google row="8" ...这样的模板变量
标签: angular nativescript