Reputation: 786
I load a component with method viewContainerRef.createComponent() and store it in a variable.
That component has child components and I need to obtain the variable from one kind of childs.
The code will be something like that:
Parent:
<div #childLoader></div>
this.loadedChild1 = this.childLoader.createComponent(child1);
Child1:
<child2></child2>
<another></another>
<child2></child2>
Child2:
@Component({
selector: 'child2',
templateUrl: 'child2.html'
})
export class Child2Component {
@Input() title: string;
public getTitle(){
return this.title;
}
}
What I'm trying after loading parent component is to acces title, other public var or in fact getTitle() method ignoring the other childs of Child1.
I'm trying to get child2 method/var from this.loadedChild1.
Is that possible?
Thank you.
Upvotes: 2
Views: 10944
Reputation: 37373
import {ViewChild, QueryList} from "@angular/core";
@Component({
selector: 'child1',
templateUrl: 'child1.html'
})
export class Child1Component {
@ViewChildren(Child2Component) childs2:QueryList<Child2Component>;
ngAfterViewInit() {
//do something
this.childs2.forEach((child2)=>{
child2.getTtile();
});
}
}
Upvotes: 1
Reputation: 91
I see that you used @Input for inputting data into the child. It's the other way around for output with @Output
In your child1 component
@Output()
notify: EventEmitter<string> = new EventEmitter<string>();
sendTitle(): void {
this.notify.emit(this.title);
}
In your parent html
<child1 (notify)="getChildTitle($event)"></child1>
In your parent component
getChildTitle(title: string): void{
console.log("Received child's title: " + title);
}
Great article on this: https://www.themarketingtechnologist.co/building-nested-components-in-angular-2/
Hope this helps!
Upvotes: 5