thp*_*pnk 28 javascript angular2-template angular2-routing angular
如何处理/提供@Input,并@Output在角2动态创建组件的属性?
这个想法是在调用createSub方法时动态创建(在这种情况下)SubComponent.分叉很好,但我如何为SubComponent中的属性提供数据.另外,如何处理/订阅SubComponent提供的事件?@Input@Output
例如: (两个部件在相同的NgModule)
AppComponent
@Component({
selector: 'app-root'
})
export class AppComponent {
someData: 'asdfasf'
constructor(private resolver: ComponentFactoryResolver, private location: ViewContainerRef) { }
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
ref.changeDetectorRef.detectChanges();
return ref;
}
onClick() {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
子
@Component({
selector: 'app-sub'
})
export class SubComponent {
@Input('data') someData: string;
@Output('onClick') onClick = new EventEmitter();
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*vić 13
您可以在创建组件时轻松绑定它:
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length, this.location.parentInjector, []);
ref.someData = { data: '123' }; // send data to input
ref.onClick.subscribe( // subscribe to event emitter
(event: any) => {
console.log('click');
}
)
ref.changeDetectorRef.detectChanges();
return ref;
}
Run Code Online (Sandbox Code Playgroud)
发送数据真的很直接,只要你想发送的数据ref.someData = data在哪里data。
从输出中获取数据也很容易,因为EventEmitter您可以简单地订阅它,并且只要您emit()从组件中获取值,您传入的 clojure 就会执行。
createSub() {
const factory = this.resolver.resolveComponentFactory(SubComponent);
const ref = this.location.createComponent(factory, this.location.length,
ref.instance.model = {Which you like to send}
ref.instance.outPut = (data) =>{ //will get called from from SubComponent}
this.location.parentInjector, []);
ref.changeDetectorRef.detectChanges();
return ref;
}
SubComponent{
public model;
public outPut = <any>{};
constructor(){ console.log("Your input will be seen here",this.model) }
sendDataOnClick(){
this.outPut(inputData)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6240 次 |
| 最近记录: |