我正在使用带有TypeScript的Angular 2。
我有一个BaseType
组件
@Component({})
export class BaseType {
protected state: string;
constructor() { }
setState(state : string) {
this.state = state;
}
}
我通过延伸ComponentOne
ComponentTwo
和BaseType
ComponentOne
@Component({})
export class ComponentOne extends BaseType {
constructor() { }
}
ComponentTwo
@Component({})
export class ComponentTwo extends BaseType {
constructor() { }
}
我使用以下代码(部分代码)
在另一个类中动态加载这两个组件let component: any;
if(/*condition to show component one*/) {
this.component = ComponentOne;
} else {
this.component = ComponentTwo;
}
//Load Component
this
.loader
.loadIntoLocation(this.component, this.el, 'field')
.then((res) => {});
当我稍后在同一个文件中使用以下内容时:
this.component.setState("state");
触发错误
TypeError: this.component.setState is not a function(…)
我应该在component
上使用哪种类型(目前为any
),或使用任何广告投放,以便在setState
上访问this.component
方法无任何问题?
提前致谢!
答案 0 :(得分:3)
遇到了问题。
setState
方法。我的代码修正了什么:
Angular 2返回loadIntoLocation
的承诺以及对新创建的Component实例的引用。
所以,我创建了另一个类型为ComponentRef
的局部变量,可以从angular2/core
加载。
但这只是一个组件参考,它不包含实际的实例。
ComponentRef
提供了另一个名为instance
的属性来访问它的方法。
工作代码
let componentRef: ComponentRef;
this
.loader
.loadIntoLocation(this.component, this.el, 'field')
.then((res) => {
componentRef = res;
//Here it works
componentRef.instance.setState("state");
});