Angular2: child component access parent class variable/function

前端 未结 5 1051
夕颜
夕颜 2020-12-02 11:47

I have a variable in the parent component that might be changed by child, parent will be using this variable in the view and thus has to propagate changes.

i         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 12:37

    What about a little trickery like NgModel does with NgForm? You have to register your parent as a provider, then load your parent in the constructor of the child.

    That way, you don't have to put [sharedList] on all your children.

    // Parent.ts
    export var parentProvider = {
        provide: Parent,
        useExisting: forwardRef(function () { return Parent; })
    };
    
    @Component({
        moduleId: module.id,
        selector: 'parent',
        template: '
    ', providers: [parentProvider] }) export class Parent { @Input() public sharedList = []; } // Child.ts @Component({ moduleId: module.id, selector: 'child', template: '
    child
    ' }) export class Child { constructor(private parent: Parent) { parent.sharedList.push('Me.'); } }

    Then your HTML

    
        
        
    
    

    You can find more information on the subject in the Angular documentation: https://angular.io/guide/dependency-injection-in-action#find-a-parent-component-by-injection

提交回复
热议问题