One of the challenges I faced was passing a property from a base component to its children, particularly when the property needed to be used in the base component constructor. I found a solution by utilizing an intermediate service because the tasks I needed to perform in the base component constructor couldn't be done within the ngInit()
method.
Initially, I attempted to use a string parameter in the constructor, like
constructor(injector: Injector, holderName: string)
, but encountered issues with this approach.
Are there any simpler alternatives to using an intermediate service for passing properties between components?
Below is an example of my child component setup:
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
providers: [DataService]
})
export class ChildComponent extends ParentComponent implements OnInit {
constructor(injector: Injector, childService: DataService) {
childService.componentName = 'Child';
super(injector, childService);
console.log('childService ' + childService.componentName)
}
ngOnInit() {
}
}
And here is my base component:
@Component({
template: ''
})
export class ParentComponent {
private componentName: string;
constructor(injector: Injector, @Optional() parentService: DataService = null) {
if (parentService !== undefined && parentService !== null) {
this.componentName = parentService.componentName;
console.log('parentService ' + parentService.componentName);
//Perform important tasks.
}
}
}
@Injectable()
export class DataService {
componentName: string = null;
}
Thank you,