I have parent component with child directive inside of it. Needs to get input data from the component in the directive.
<my-parent [data]="'Hello from parent'">
<input myChild>
</my-parent>
Parent Component
@Component({
selector: 'my-parent',
template: `
<ng-content select="[myChild]"></ng-content>
`
})
export class ParentComponent {
@Input() data: string;
}
Child Directive
@Directive({
selector: '[myChild]'
})
export class ChildDirective implements OnInit {
value: string;
ngOnInit() {
// needs to get data from parent component here
}
}
I can inject parent component into directive, but I don't want to do this, because it increases the risk of cyclical dependencies.
I can use @ContentChild in ParentComponent and pass data in AfterContentInit via public property, but I am not sure when this property will be available in ChildDirective, should I use AfterContentChecked for this case or not?
Parent Component
@ContentChild(ChildDirective, {static: true}) child: ChildDirective;
ngAfterContentInit() {
this.child.value = this.data;
}
Child Directive
value: string;
ngAfterContentChecked() {
// will be available data from parent here?
}
Maybe I should use service to share data between the component and the directive?
https://stackblitz.com/edit/angular-pass-data-to-child-directive